<html>
<head>
<meta name="collection" content="exclude">

<title>The Java Language Specification
 Types, Values, and Variables</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
 
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="3.doc.html">Prev</a> | <a href="5.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<hr><br>
 
<a name="95843"></a>
<p><strong>
CHAPTER
 4 </strong></p>
<a name="95845"></a>
<h1>Types, Values, and Variables</h1>
<hr><p>
<a name="45200"></a>
Java is a <i>strongly typed</i> language, which means that every variable and every 
expression has a type that is known at compile time. Types limit the values that a 
variable <a href="4.doc.html#18470">(&#167;4.5)</a> can hold or that an expression can produce, limit the operations 
supported on those values, and determine the meaning of the operations. Strong 
typing helps detect errors at compile time.
<p><a name="50743"></a>
The types of the Java language are divided into two categories: primitive types and reference types. The primitive types <a href="4.doc.html#85587">(&#167;4.2)</a> are the <code>boolean</code> type and the numeric types. The numeric types are the integral types <code>byte</code>, <code>short</code>, <code>int</code>, <code>long</code>, and <code>char</code>, and the floating-point types <code>float</code> and <code>double</code>. The reference types <a href="4.doc.html#9317">(&#167;4.3)</a> are class types, interface types, and array types. There is also a special null type. An object <a href="4.doc.html#12028">(&#167;4.3.1)</a> in Java is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class <code>Object</code> <a href="4.doc.html#11055">(&#167;4.3.2)</a>. String literals are represented by <code>String</code> objects <a href="4.doc.html#26992">(&#167;4.3.3)</a>.<p>
<a name="50838"></a>
Types are the same <a href="4.doc.html#52197">(&#167;4.3.4)</a> if they have the same fully qualified names and are loaded by the same class loader. Names of types are used <a href="4.doc.html#25948">(&#167;4.4)</a> in declarations, in casts, in class instance creation expressions, in array creation expressions, and in <code>instanceof</code> operator expressions.<p>
<a name="50800"></a>
A variable <a href="4.doc.html#18470">(&#167;4.5)</a> is a storage location. A variable of a primitive type always holds a value of that exact type. A variable of a class type <i>T</i><em></em> can hold a null reference or a reference to an instance of class <i>T</i><em></em> or of any class that is a subclass of <i>T</i>. A variable of an interface type can hold a null reference or a reference to any instance of any class that implements the interface. If <i>T</i> is a primitive type, then a variable of type "array of <i>T</i><em></em>" can hold a null reference or a reference to any array of type "array of <i>T</i><em></em>"; if <i>T</i> is a reference type, then a variable of type "array of <i>T</i><em></em>" can hold a null reference or a reference to any array of type "array of <i>S</i><em></em>" such that type <i>S</i><em></em> is assignable <a href="5.doc.html#170768">(&#167;5.2)</a> to type <i>T</i><em></em>. A variable of type <code>Object</code> can hold a null reference or a reference to any object, whether class instance or array.<p>
<a name="11128"></a>
<h2>4.1    The Kinds of Types and Values</h2>
<a name="10737"></a>
There are two kinds of <i>types</i> in Java: primitive types <a href="4.doc.html#85587">(&#167;4.2)</a> and reference types 
<a href="4.doc.html#9317">(&#167;4.3)</a>. There are, correspondingly, two kinds of data values that can be stored in 
variables, passed as arguments, returned by methods, and operated on: primitive 
values <a href="4.doc.html#85587">(&#167;4.2)</a> and reference values <a href="4.doc.html#9317">(&#167;4.3)</a>.
<p><ul><pre>
<i>Type:<br>
</i>	<i>PrimitiveType<br>
	ReferenceType
</i></pre></ul><a name="23953"></a>
There is also a special <i>null type</i>, the type of the expression <code>null</code>, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the Java programmer can ignore the null type and just pretend that <code>null</code> is merely a special literal that can be of any reference type.<p>
<a name="85587"></a>
<h2>4.2    Primitive Types and Values</h2>
<a name="9122"></a>
A <i>primitive type</i> is predefined by the Java language and named by its reserved 
keyword <a href="3.doc.html#229308">(&#167;3.9)</a>:
<p><ul><pre>
<i>PrimitiveType:<br>
	NumericType<br>
	</i><code>boolean
</code>
<i>NumericType:<br>
	IntegralType<br>
	FloatingPointType
</i>
<i>IntegralType:</i> <i>one</i> <i>of<br>
</i>	<code>byte short int long char
</code>
<i>FloatingPointType:</i> <i>one</i> <i>of<br>
</i><code>	float double
</code></pre></ul><a name="50919"></a>
Primitive values do not share state with other primitive values. A variable whose type is a primitive type always holds a primitive value of that same type. The value of a variable of primitive type can be changed only by assignment operations on that variable.<p>
<a name="9137"></a>
The <i>numeric types</i> are the integral types and the floating-point types. <p>
<a name="88061"></a>
The <i>integral types</i> are <code>byte</code>, <code>short</code>, <code>int</code>, and <code>long</code>, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and <code>char</code>, whose values are 16-bit unsigned integers representing Unicode characters.<p>
<a name="88062"></a>
The <i>floating-point types</i> are <code>float</code>, whose values are 32-bit IEEE 754 floating-point numbers, and <code>double</code>, whose values are 64-bit IEEE 754 floating-point numbers.<p>
<a name="50913"></a>
The <code>boolean</code> type has exactly two values: <code>true</code> and <code>false.</code><p>
<a name="9151"></a>
<h3>4.2.1    Integral Types and Values</h3>
<a name="50950"></a>
The values of the integral types are integers in the following ranges:
<p><ul><a name="9163"></a>
<li>For <code>byte</code>, from -128 to 127, inclusive
<a name="9164"></a>
<li>For <code>short</code>, from -32768 to 32767, inclusive
<a name="9165"></a>
<li>For <code>int</code>, from -2147483648 to 2147483647, inclusive
<a name="9166"></a>
<li>For <code>long</code>, from -9223372036854775808 to 9223372036854775807, inclusive
<a name="51034"></a>
<li>For <code>char</code>, from <code>'\u0000'</code> to <code>'\uffff'</code> inclusive, that is, from 0 to 65535
</ul><a name="51035"></a>
<h3>4.2.2    Integer Operations</h3>
<a name="29775"></a>
Java provides a number of operators that act on integral values:
<p><ul><a name="10358"></a>
<li>The comparison operators, which result in a value of type <code>boolean</code>:
<ul>
<a name="9181"></a>
<li>The numerical comparison operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> <a href="15.doc.html#153654">(&#167;15.19.1)</a>
<a name="17601"></a>
<li>The numerical equality operators <code>==</code> and <code>!=</code> <a href="15.doc.html#5198">(&#167;15.20.1)</a>
</ul>
<a name="10365"></a>
<li>The numerical operators, which result in a value of type <code>int</code> or <code>long</code>:
<ul>
<a name="18334"></a>
<li>The unary plus and minus operators <code>+</code> and <code>-</code> (<a href="15.doc.html#24924">&#167;15.14.3</a>, <a href="15.doc.html#236345">&#167;15.14.4</a>)
<a name="17539"></a>
<li>The multiplicative operators <code>*</code>, <code>/</code>, and <code>%</code> <a href="15.doc.html#239829">(&#167;15.16)</a>
<a name="19482"></a>
<li>The additive operators <code>+</code> and <code>-</code> <a href="15.doc.html#13510">(&#167;15.17.2)</a>
<a name="24026"></a>
<li>The increment operator <code>++</code>, both prefix <a href="15.doc.html#39547">(&#167;15.14.1)</a> and postfix <a href="15.doc.html#39438">(&#167;15.13.2)</a>
<a name="24036"></a>
<li>The decrement operator <code>--</code>, both prefix <a href="15.doc.html#239136">(&#167;15.14.2)</a> and postfix <a href="15.doc.html#4987">(&#167;15.13.3)</a>
<a name="19496"></a>
<li>The signed and unsigned shift operators <code>&lt;&lt;</code>, <code>&gt;&gt;</code>, and <code>&gt;&gt;&gt;</code> <a href="15.doc.html#5121">(&#167;15.18)</a>
<a name="51061"></a>
<li>The bitwise complement operator <code>~</code> <a href="15.doc.html#5017">(&#167;15.14.5)</a>
<a name="17770"></a>
<li>The integer bitwise operators <code>&amp;</code>, <code>|</code>, and <code>^</code> <a href="15.doc.html#5233">(&#167;15.21.1)</a>
</ul>
<a name="19469"></a>
<li>The conditional operator <code>? :</code> <a href="15.doc.html#5257">(&#167;15.24)</a>
<a name="18373"></a>
<li>The cast operator, which can convert from an integral value to a value of any specified numeric type (<a href="5.doc.html#176921">&#167;5.4</a>, <a href="15.doc.html#238146">&#167;15.15</a>)
<a name="17774"></a>
<li>The string concatenation operator <code>+</code> <a href="15.doc.html#39990">(&#167;15.17.1)</a>, which, when given a <code>String</code> operand and an integral operand, will convert the integral operand to a <code>String</code> representing its value in decimal form, and then produce a newly created <code>String</code> that is the concatenation of the two strings
</ul><a name="51025"></a>
Other useful constructors, methods, and constants are predefined in the classes 
<code>Integer</code> <a href="javalang.doc6.html#14348">(&#167;20.7)</a>, <code>Long</code> <a href="javalang.doc7.html#46750">(&#167;20.8)</a>, and <code>Character</code> <a href="javalang.doc4.html#14345">(&#167;20.5)</a>.
<p><a name="28057"></a>
If an integer operator other than a shift operator has at least one operand of type <code>long</code>, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type <code>long</code>. If the other operand is not <code>long</code>, it is first widened <a href="5.doc.html#25222">(&#167;5.1.2)</a> to type <code>long</code> by numeric promotion <a href="5.doc.html#26917">(&#167;5.6)</a>. Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type <code>int</code>. If either operand is not an <code>int</code>, it is first widened to type <code>int</code> by numeric promotion.<p>
<a name="9194"></a>
The built-in integer operators do not indicate overflow or underflow in any way. The only numeric operators that can throw an exception <a href="11.doc.html#44043">(&#167;11)</a> are the integer divide operator <code>/</code> <a href="15.doc.html#5047">(&#167;15.16.2)</a> and the integer remainder operator <code>%</code> <a href="15.doc.html#24956">(&#167;15.16.3)</a>, which throw an <code>ArithmeticException</code> if the right-hand operand is zero. <p>
<a name="86654"></a>
The example:<p>
<pre><a name="51117"></a>
class Test {
<a name="51118"></a>	public static void main(String[] args) {
<a name="51119"></a>		int i = 1000000;
<a name="51254"></a>		System.out.println(i * i);
<a name="51216"></a>		long l = i;
<a name="86535"></a>		System.out.println(l * l);
<a name="86536"></a>		System.out.println(20296 / (l - i));
<a name="86537"></a>	}
<a name="86538"></a>}
</pre><a name="51131"></a>
produces the output:
<p><pre><a name="51149"></a>
-727379968
<a name="51133"></a>1000000000000
</pre><a name="51199"></a>
and then encounters an <code>ArithmeticException</code> in the division by <code>l</code> <code>-</code> <code>i</code>, because 
<code>l</code> <code>-</code> <code>i</code> is zero. The first multiplication is performed in 32-bit precision, whereas the 
second multiplication is a <code>long</code> multiplication. The value <code>-727379968</code> is the decimal
value of the low 32 bits of the mathematical result, <code>1000000000000</code>, which is 
a value too large for type <code>int</code>.
<p><a name="51203"></a>
Any value of any integral type may be cast to or from any numeric type. There are no casts between integral types and the type <code>boolean</code>.<p>
<a name="9208"></a>
<h3>4.2.3    Floating-Point Types and Values</h3>
<a name="87606"></a>
The floating-point types are <code>float</code> and <code>double</code>, representing the single-precision 
32-bit and double-precision 64-bit format IEEE 754 values and operations as 
specified in <i>IEEE Standard for Binary Floating-Point Arithmetic</i>, ANSI/IEEE 
Standard 754-1985 (IEEE, New York).
<p><a name="88071"></a>
The IEEE 754 standard includes not only positive and negative sign-magnitude numbers, but also positive and negative zeros, positive and negative <i>infinities</i>, and a special <i>Not-a-Number </i>(hereafter abbreviated NaN). The NaN value is used to represent the result of certain operations such as dividing zero by zero. NaN constants of both <code>float</code> and <code>double</code> type are predefined as <code>Float.NaN</code> <a href="javalang.doc8.html#1411">(&#167;20.9.5)</a> and <code>Double.NaN</code> <a href="javalang.doc9.html#13844">(&#167;20.10.5)</a>.<p>
<a name="9219"></a>
The finite nonzero values of type <code>float</code> are of the form <img src="4.doc.anc.gif">, where <i>s</i> is +1 or -1, <i>m</i> is a positive integer less than <img src="4.doc.anc2.gif">, and <i>e</i> is an integer between -149 and 104, inclusive. Values of that form such that <i>m</i> is positive but less than <img src="4.doc.anc5.gif"> and <i>e</i> is equal to -149 are said to be <i>denormalized</i>.<p>
<a name="9223"></a>
The finite nonzero values of type <code>double</code> are of the form <img src="4.doc.anc1.gif">, where <i>s</i> is +1 or -1, <i>m</i> is a positive integer less than <img src="4.doc.anc3.gif">, and <i>e</i> is an integer between -1075 and 970, inclusive. Values of that form such that <i>m</i> is positive but less than <img src="4.doc.anc6.gif"> and <i>e</i> is equal to -1075 are said to be <i>denormalized</i>.<p>
<a name="86665"></a>
Except for NaN, floating-point values are <i>ordered</i>; arranged from smallest to largest, they are negative infinity, negative finite nonzero values, negative zero, positive zero, positive finite nonzero values, and positive infinity.<p>
<a name="86666"></a>
Positive zero and negative zero compare equal; thus the result of the expression <code>0.0==-0.0</code> is <code>true</code> and the result of <code>0.0&gt;-0.0</code> is <code>false</code>. But other operations can distinguish positive and negative zero; for example, <code>1.0/0.0</code> has the value positive infinity, while the value of <code>1.0/-0.0</code> is negative infinity. The operations <code>Math.min</code> and <code>Math.max</code> also distinguish positive zero and negative zero.<p>
<a name="16083"></a>
NaN is <i>unordered</i>, so the numerical comparison operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> return <code>false</code> if either or both operands are NaN <a href="15.doc.html#153654">(&#167;15.19.1)</a>. The equality operator <code>==</code> returns <code>false</code> if either operand is NaN, and the inequality operator <code>!=</code> returns <code>true</code> if either operand is NaN <a href="15.doc.html#5198">(&#167;15.20.1)</a>. In particular, <code>x!=x</code> is <code>true</code> if and only if <code>x</code> is NaN, and <code>(x&lt;y)</code> <code>==</code> <code>!(x&gt;=y)</code> will be <code>false</code> if <code>x</code> or <code>y</code> is NaN.<p>
<a name="16093"></a>
Any value of a floating-point type may be cast to or from any numeric type. There are no casts between floating-point types and the type <code>boolean</code>.<p>
<a name="9249"></a>
<h3>4.2.4    Floating-Point Operations</h3>
<a name="9981"></a>
Java provides a number of operators that act on floating-point values:
<p><ul><a name="52058"></a>
<li>The comparison operators, which result in a value of type <code>boolean</code>:
<ul>
<a name="52062"></a>
<li>The numerical comparison operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> <a href="15.doc.html#153654">(&#167;15.19.1)</a>
<a name="52066"></a>
<li>The numerical equality operators <code>==</code> and <code>!=</code> <a href="15.doc.html#5198">(&#167;15.20.1)</a>
</ul>
<a name="52069"></a>
<li>The numerical operators, which result in a value of type <code>float</code> or <code>double</code>:
<ul>
<a name="52076"></a>
<li>The unary plus and minus operators <code>+</code> and <code>-</code> (<a href="15.doc.html#24924">&#167;15.14.3</a>, <a href="15.doc.html#236345">&#167;15.14.4</a>)
<a name="24115"></a>
<li>The multiplicative operators <code>*</code>, <code>/</code>, and <code>%</code> <a href="15.doc.html#239829">(&#167;15.16)</a>
<a name="24119"></a>
<li>The additive operators <code>+</code> and <code>-</code> <a href="15.doc.html#13510">(&#167;15.17.2)</a>
<a name="24126"></a>
<li>The increment operator <code>++</code>, both prefix <a href="15.doc.html#39547">(&#167;15.14.1)</a> and postfix <a href="15.doc.html#39438">(&#167;15.13.2)</a>
<a name="24107"></a>
<li>The decrement operator <code>--</code>, both prefix <a href="15.doc.html#239136">(&#167;15.14.2)</a> and postfix <a href="15.doc.html#4987">(&#167;15.13.3)</a>
</ul>
<a name="19446"></a>
<li>The conditional operator <code>? :</code> <a href="15.doc.html#5257">(&#167;15.24)</a>
<a name="11998"></a>
<li>The cast operator, which can convert from a floating-point value to a value of any specified numeric type (<a href="5.doc.html#176921">&#167;5.4</a>, <a href="15.doc.html#238146">&#167;15.15</a>)
<a name="21842"></a>
<li>The string concatenation operator <code>+</code> <a href="15.doc.html#39990">(&#167;15.17.1)</a>, which, when given a <code>String</code> operand and a floating-point operand, will convert the floating-point operand to a <code>String</code> representing its value in decimal form (without information loss), and then produce a newly created <code>String</code> by concatenating the two strings
</ul><a name="12009"></a>
Other useful constructors, methods, and constants are predefined in the classes 
<code>Float</code> <a href="javalang.doc8.html#14394">(&#167;20.9)</a>, <code>Double</code> <a href="javalang.doc9.html#14390">(&#167;20.10)</a>, and <code>Math</code> <a href="javalang.doc10.html#47547">(&#167;20.11)</a>.
<p><a name="12005"></a>
If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.<p>
<a name="51262"></a>
If at least one of the operands to a numerical operator is of type <code>double</code>, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type <code>double</code>. (If the other operand is not a <code>double</code>, it is first widened to type <code>double</code> by numeric promotion <a href="5.doc.html#26917">(&#167;5.6)</a>.) Otherwise, the operation is carried out using 32-bit floating-point arithmetic, and the result of the numerical operator is a value of type <code>float. </code>If the other operand is not a <code>float</code>, it is first widened to type <code>float</code> by numeric promotion.<p>
<a name="9265"></a>
Operators on floating-point numbers behave exactly as specified by IEEE 754. In particular, Java requires support of IEEE 754 <i>denormalized</i> floating-point numbers and <i>gradual underflow</i>, which make it easier to prove desirable properties of particular numerical algorithms. Floating-point operations in Java do not "flush to zero" if the calculated result is a denormalized number.<p>
<a name="9274"></a>
Java requires that floating-point arithmetic behave as if every floating-point operator rounded its floating-point result to the result precision. <i>Inexact</i> results must be rounded to the representable value nearest to the infinitely precise result; if the two nearest representable values are equally near, the one with its least significant bit zero is chosen. This is the IEEE 754 standard's default rounding mode known as <i>round to nearest</i>.<p>
<a name="10346"></a>
Java uses <i>round toward zero</i> when converting a floating value to an integer <a href="5.doc.html#175672">(&#167;5.1.3)</a>, which acts, in this case, as though the number were truncated, discarding the mantissa bits. Rounding toward zero chooses at its result the format's value closest to and no greater in magnitude than the infinitely precise result.<p>
<a name="9290"></a>
Java floating-point operators produce no exceptions <a href="11.doc.html#44043">(&#167;11)</a>. An operation that overflows produces a signed infinity, an operation that underflows produces a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result. As has already been described, NaN is unordered, so a numeric comparison operation involving one or two NaNs returns <code>false</code> and any <code>!=</code> comparison involving NaN returns <code>true</code>, including <code>x!=x</code> when <code>x</code> is NaN.<p>
<a name="9291"></a>
The example program:<p>
<pre><a name="9292"></a>
class Test {
<a name="45603"></a>
	public static void main(String[] args) {
<a name="49672"></a>
		// An example of overflow:
<a name="49673"></a>		double d = 1e308;
<a name="86539"></a>		System.out.print("overflow produces infinity: ");
<a name="86540"></a>		System.out.println(d + "*10==" + d*10);
<a name="86541"></a>
		// An example of gradual underflow:
<a name="49678"></a>		d = 1e-305 * Math.PI;
<a name="85624"></a>		System.out.print("gradual underflow: " + d + "\n &#32; &#32; &#32;");
<a name="49679"></a>		for (int i = 0; i &lt; 4; i++)
<a name="49680"></a>			System.out.print(" " + (d /= 100000));
<a name="49755"></a>		System.out.println();
<a name="49756"></a>
		// An example of NaN:
<a name="49757"></a>		System.out.print("0.0/0.0 is Not-a-Number: ");
<a name="49685"></a>		d = 0.0/0.0;
<a name="85896"></a>		System.out.println(d);
<a name="49698"></a>
		// An example of inexact results and rounding:
<a name="49701"></a>		System.out.print("inexact results with float:");
<a name="49702"></a>		for (int i = 0; i &lt; 100; i++) {
<a name="49703"></a>			float z = 1.0f / i;
<a name="49704"></a>			if (z * i != 1.0f)
<a name="49705"></a>				System.out.print(" " + i);
<a name="49706"></a>		}
<a name="20012"></a>		System.out.println();
<a name="85847"></a>
		// Another example of inexact results and rounding:
<a name="49707"></a>		System.out.print("inexact results with double:");
<a name="49708"></a>		for (int i = 0; i &lt; 100; i++) {
<a name="49709"></a>			double z = 1.0 / i;
<a name="49710"></a>			if (z * i != 1.0)
<a name="49711"></a>				System.out.print(" " + i);
<a name="49712"></a>		}
<a name="49713"></a>		System.out.println();
<a name="10212"></a>
		// An example of cast to integer rounding:
<a name="49718"></a>		System.out.print("cast to int rounds toward 0: ");
<a name="49719"></a>		d = 12345.6;
<a name="49720"></a>		System.out.println((int)d + " " + (int)(-d));
<a name="49721"></a>	}
<a name="49722"></a>}
</pre><a name="23297"></a>
produces the output:
<p><pre><a name="23314"></a>
overflow produces infinity: 1.0e+308*10==Infinity
<a name="23315"></a>gradual underflow: 3.141592653589793E-305
<a name="85613"></a>	3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0
<a name="23316"></a>0.0/0.0 is Not-a-Number: NaN
<a name="23317"></a>inexact results with float: 0 41 47 55 61 82 83 94 97
<a name="23318"></a>inexact results with double: 0 49 98
<a name="23303"></a>cast to int rounds toward 0: 12345 -12345
</pre><a name="22309"></a>
This example demonstrates, among other things, that gradual underflow can result in a gradual loss of precision.<p>
<a name="11717"></a>
The inexact results when <code>i</code> is <code>0</code> involve division by zero, so that <code>z</code> becomes positive infinity, and <code>z</code> <code>*</code> <code>0</code> is NaN, which is not equal to <code>1.0</code>.<p>
<a name="11527"></a>
<h3>4.2.5    The <code>boolean</code> Type and <code>boolean</code> Values</h3>
<a name="9295"></a>
The <code>boolean</code> type represents a logical quantity with two possible values, indicated
by the literals <code>true</code> and <code>false</code> <a href="3.doc.html#49652">(&#167;3.10.3)</a>. The boolean operators are:
<p><ul><a name="17733"></a>
<li>The relational operators <code>==</code> and <code>!=</code> <a href="15.doc.html#54508">(&#167;15.20.2)</a>
<a name="17734"></a>
<li>The logical-complement operator <code>!</code> <a href="15.doc.html#13350">(&#167;15.14.6)</a>
<a name="17736"></a>
<li>The logical operators <code>&amp;</code>, <code>^</code>, and <code>|</code> <a href="15.doc.html#5242">(&#167;15.21.2)</a>
<a name="17737"></a>
<li>The conditional-and and conditional-or operators <code>&amp;&amp;</code> <a href="15.doc.html#5247">(&#167;15.22)</a> and <code>||</code> <a href="15.doc.html#54532">(&#167;15.23)</a>
<a name="19467"></a>
<li>The conditional operator <code>? :</code> <a href="15.doc.html#5257">(&#167;15.24)</a>
<a name="21871"></a>
<li>The string concatenation operator <code>+</code> <a href="15.doc.html#39990">(&#167;15.17.1)</a>, which, when given a <code>String</code> operand and a boolean operand, will convert the boolean operand to a <code>String</code> (either <code>"true"</code> or <code>"false"</code>), and then produce a newly created <code>String</code> that is the concatenation of the two strings
</ul><a name="17738"></a>
Boolean expressions determine the control flow in several kinds of statements:
<p><ul><a name="17742"></a>
<li>The <code>if</code> statement <a href="14.doc.html#5991">(&#167;14.8)</a>
<a name="17743"></a>
<li>The <code>while</code> statement <a href="14.doc.html#237277">(&#167;14.10)</a>
<a name="17745"></a>
<li>The <code>do</code> statement <a href="14.doc.html#6045">(&#167;14.11)</a>
<a name="17747"></a>
<li>The <code>for</code> statement <a href="14.doc.html#24588">(&#167;14.12)</a>
</ul><a name="48454"></a>
A <code>boolean</code> expression also determines which subexpression is evaluated in the 
conditional <code>?&#32;:</code> operator <a href="15.doc.html#5257">(&#167;15.24)</a>.
<p><a name="48458"></a>
Only <code>boolean</code> expressions can be used in control flow statements and as the first operand of the conditional operator <code>?&#32;:</code>. An integer <code>x</code> can be converted to a <code>boolean</code>, following the C language convention that any nonzero value is <code>true</code>, by the expression <code>x!=0</code>. An object reference <code>obj</code> can be converted to a <code>boolean</code>, following &#32;the C language convention that any reference other than <code>null</code> is <code>true</code>, by the expression <code>obj!=null</code>.<p>
<a name="9299"></a>
A cast of a <code>boolean</code> value to type <code>boolean</code> is allowed <a href="5.doc.html#25209">(&#167;5.1.1)</a>; no other casts on type <code>boolean</code> are allowed. A <code>boolean</code> can be converted to a string by string conversion <a href="5.doc.html#176921">(&#167;5.4)</a>.<p>
<a name="9317"></a>
<h2>4.3    Reference Types and Values</h2>
<a name="9664"></a>
There are three kinds of <i>reference types</i>: class types <a href="8.doc.html#3857">(&#167;8)</a>, interface types <a href="9.doc.html#238678">(&#167;9)</a>, and 
array types <a href="10.doc.html#27803">(&#167;10)</a>.
<p><ul><pre>
<i>ReferenceType:<br>
	ClassOrInterfaceType<br>
	ArrayType
</i>
<i>ClassOrInterfaceType:<br>
	ClassType<br>
	InterfaceType
</i>
<i>ClassType:<br>
	TypeName
</i>
<i>InterfaceType:<br>
	TypeName
</i>
<i>ArrayType:<br>
</i>	<i>Type</i><code> [ ]
</code></pre></ul><a name="9678"></a>
Names are described in <a href="6.doc.html#48086">&#167;6</a>; type names in <a href="6.doc.html#20569">&#167;6.5</a> and, specifically, <a href="6.doc.html#21721">&#167;6.5.4</a>.
<p><a name="87599"></a>
The sample code:<p>
<pre><br><a name="10435"></a>class Point { int[] metrics; }
<br><a name="10414"></a>interface Move { void move(int deltax, int deltay); }
</pre><a name="11032"></a>
declares a class type <code>Point</code>, an interface type <code>Move</code>, and uses an array type <code>int[]</code> 
(an array of <code>int</code>) to declare the field <code>metrics</code> of the class <code>Point</code>.
<p><a name="12028"></a>
<h3>4.3.1    Objects</h3>
<a name="86707"></a>
An <i>object</i> is a <i>class</i> <i>instance</i> or an array.
<p><a name="86710"></a>
The reference values (often just <i>references</i>) are <i>pointers </i>to these objects, and a special null reference, which refers to no object.<p>
<a name="49853"></a>
A class instance is explicitly created by a class instance creation expression <a href="15.doc.html#41147">(&#167;15.8)</a>, or by invoking the <code>newInstance</code> method of class <code>Class</code> <a href="javalang.doc2.html#28532">(&#167;20.3.8)</a>. An array is explicitly created by an array creation expression <a href="15.doc.html#41147">(&#167;15.8)</a>.<p>
<a name="49899"></a>
A new class instance is implicitly created when the string concatenation operator + <a href="15.doc.html#39990">(&#167;15.17.1)</a> is used in an expression, resulting in a new object of type <code>String</code> (<a href="4.doc.html#26992">&#167;4.3.3</a>, <a href="javalang.doc11.html#14460">&#167;20.12</a>). A new array object is implicitly created when an array initializer expression <a href="10.doc.html#11358">(&#167;10.6)</a> is evaluated; this can occur when a class or interface is initialized <a href="12.doc.html#44557">(&#167;12.4)</a>, when a new instance of a class is created <a href="15.doc.html#41147">(&#167;15.8)</a>, or when a local variable declaration statement is executed <a href="14.doc.html#5920">(&#167;14.3)</a>.<p>
<a name="49960"></a>
Many of these cases are illustrated in the following example:<p>
<pre><a name="49961"></a>
class Point {
<a name="51683"></a>	int x, y;
<a name="86692"></a>	Point() { System.out.println("default"); }
<a name="86696"></a>	Point(int x, int y) { this.x = x; this.y = y; }
<a name="51733"></a>
	// A Point instance is explicitly created at class initialization time:
<a name="51732"></a>	static Point origin = new Point(0,0);
<a name="51734"></a>
	// A String can be implicitly created by a + operator:
<a name="51682"></a>	public String toString() {<br>
		return "(" + x + "," + y + ")";<br>
	}
<a name="51684"></a>}
<br><a name="51685"></a>
class Test {
<a name="51686"></a>	public static void main(String[] args) {
<a name="51735"></a>		// A Point is explicitly created using newInstance:
<a name="23341"></a>		Point p = null;
<a name="23324"></a>		try {
<a name="51687"></a>			p = (Point)Class.forName("Point").newInstance();
<a name="23327"></a>		} catch (Exception e) {
<a name="23350"></a>			System.out.println(e);
<a name="23351"></a>		}
<br><a name="51738"></a>
		// An array is implicitly created by an array constructor:
<a name="51688"></a>		Point a[] = { new Point(0,0), new Point(1,1) };
<br><a name="51757"></a>
		// Strings are implicitly created by + operators:
<a name="51689"></a>		System.out.println("p: " + p);
<a name="51690"></a>		System.out.println("a: { " + a[0] + ", "<br>
										  &#32;+ a[1] + " }");
<br><a name="51745"></a>
		// An array is explicitly created by an array creation expression:
<a name="51693"></a>		String sa[] = new String[2];
<a name="51697"></a>		sa[0] = "he"; sa[1] = "llo";
<a name="51698"></a>		System.out.println(sa[0] + sa[1]);
<a name="51699"></a>	}
<a name="49976"></a>}
</pre><a name="87328"></a>
which produces the output:
<p><pre><a name="87331"></a>
default
<a name="87332"></a>p: (0,0)
<a name="87333"></a>a: { (0,0), (1,1) }
<a name="87329"></a>hello
</pre><a name="49965"></a>
The operators on references to objects are:<p>
<ul><a name="31321"></a>
<li>Field access, using either a qualified name <a href="6.doc.html#33916">(&#167;6.6)</a> or a field access expression <a href="15.doc.html#41267">(&#167;15.10)</a>
<a name="31328"></a>
<li>Method invocation <a href="15.doc.html#20448">(&#167;15.11)</a>
<a name="31378"></a>
<li>The cast operator (<a href="5.doc.html#176921">&#167;5.4</a>, <a href="15.doc.html#238146">&#167;15.15</a>)
<a name="31345"></a>
<li>The string concatenation operator <code>+</code> <a href="15.doc.html#39990">(&#167;15.17.1)</a>, which, when given a <code>String</code> operand and a reference, will convert the reference to a <code>String</code> by invoking the <code>toString</code> method <a href="javalang.doc1.html#1152">(&#167;20.1.2)</a> of the referenced object (using <code>"null"</code> if either the reference or the result of <code>toString</code> is a null reference), and then will produce a newly created <code>String</code> that is the concatenation of the two strings
<a name="31399"></a>
<li>The <code>instanceof</code> operator <a href="15.doc.html#80289">(&#167;15.19.2)</a>
<a name="31306"></a>
<li>The reference equality operators <code>==</code> and <code>!=</code> <a href="15.doc.html#236163">(&#167;15.20.3)</a>
<a name="19595"></a>
<li>The conditional operator <code>?&#32;:</code> <a href="15.doc.html#5257">(&#167;15.24)</a>.
</ul><a name="28239"></a>
There may be many references to the same object. Most objects have state, stored in the fields of objects that are instances of classes or in the variables that are the components of an array object. If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.<p>
<a name="87600"></a>
The example program:<p>
<pre><a name="11036"></a>class Value { int val; }
</pre><pre><a name="87412"></a>
class Test {
<a name="87413"></a>	public static void main(String[] args) {
<a name="87414"></a>		int i1 = 3;
<a name="52134"></a>		int i2 = i1;
<a name="52135"></a>		i2 = 4;
<a name="50355"></a>		System.out.print("i1==" + i1);
<a name="50357"></a>		System.out.println(" but i2==" + i2);
<a name="50359"></a>		Value v1 = new Value();
<a name="50361"></a>		v1.val = 5;
<a name="52142"></a>		Value v2 = v1;
<a name="52143"></a>		v2.val = 6;
<a name="50363"></a>		System.out.print("v1.val==" + v1.val);
<a name="50365"></a>		System.out.println(" and v2.val==" + v2.val);
<a name="50367"></a>	}
<a name="50369"></a>}
</pre><a name="11050"></a>
produces the output:
<p><pre><a name="11051"></a>
i1==3 but i2==4
<a name="45608"></a>v1.val==6 and v2.val==6
</pre><a name="11053"></a>
because <code>v1.val</code> and <code>v2.val</code> reference the same instance variable <a href="4.doc.html#28536">(&#167;4.5.3)</a> in the 
one <code>Value</code> object created by the only <code>new</code> expression, while <code>i1</code> and <code>i2</code> are different
variables.
<p><a name="17783"></a>
See <a href="10.doc.html#27803">&#167;10</a> and <a href="15.doc.html#46168">&#167;15.9</a> for examples of the creation and use of arrays.<p>
<a name="17053"></a>
Each object has an associated lock <a href="17.doc.html#28460">(&#167;17.13)</a>, which is used by <code>synchronized</code> methods <a href="8.doc.html#78188">(&#167;8.4.3)</a> and the <code>synchronized</code> statement <a href="14.doc.html#79287">(&#167;14.17)</a> to provide control over concurrent access to state by multiple threads (<a href="17.doc.html#28457">&#167;17.12</a>, <a href="javalang.doc18.html#2658">&#167;20.20</a>).<p>
<a name="11055"></a>
<h3>4.3.2    The Class <code>Object</code></h3>
<a name="26999"></a>
The standard class <code>Object</code> is a superclass <a href="8.doc.html#15372">(&#167;8.1)</a> of all other classes. A variable of 
type <code>Object</code> can hold a reference to any object, whether it is an instance of a class 
or an array <a href="10.doc.html#27803">(&#167;10)</a>. All class and array types inherit the methods of class <code>Object</code>, 
which are summarized here and completely specified in <a href="javalang.doc1.html#46442">&#167;20.1</a>:
<p><pre><a name="12035"></a>package java.lang;
</pre><pre><a name="45609"></a>
public class Object {
<a name="51634"></a>	public final Class getClass() { . . . }
<a name="51635"></a>	public String toString() { . . . }
<a name="51636"></a>	public boolean equals(Object obj) { . . . }
<a name="51637"></a>	public int hashCode() { . . . }
<a name="51638"></a>	protected Object clone()
<a name="86088"></a>		throws CloneNotSupportedException { . . . }
<a name="87378"></a>	public final void wait()<br>
		throws IllegalMonitorStateException,<br>
			InterruptedException { . . . }
<a name="51641"></a>	public final void wait(long millis)
<a name="87381"></a>		throws IllegalMonitorStateException,
<a name="87383"></a>			InterruptedException { . . . }
<a name="51642"></a>	public final void wait(long millis, int nanos) { . . . }
<a name="87385"></a>		throws IllegalMonitorStateException,
<a name="87386"></a>			InterruptedException { . . . }
<a name="87373"></a>	public final void notify() { . . . }
<a name="87374"></a>		throws IllegalMonitorStateException
<a name="87387"></a>	public final void notifyAll() { . . . }
<a name="87389"></a>		throws IllegalMonitorStateException
<a name="51644"></a>	protected void finalize()
<a name="86090"></a>		throws Throwable { . . . }
<a name="51645"></a>}
</pre><a name="45610"></a>
The members of <code>Object</code> are as follows:
<p><ul><a name="12048"></a>
<li>The method <code>getClass</code> returns the <code>Class</code> <a href="javalang.doc2.html#14342">(&#167;20.3)</a> object that represents the class of the object. A <code>Class</code> object exists for each reference type. It can be used, for example, to discover the fully qualified name of a class, its members, its immediate superclass, and any interfaces that it implements. A class method that is declared <code>synchronized</code> <a href="8.doc.html#55408">(&#167;8.4.3.5)</a> synchronizes on the lock associated with the <code>Class</code> object of the class.
<a name="12066"></a>
<li>The method <code>toString</code> returns a <code>String</code> representation of the object.
<a name="12104"></a>
<li>The methods <code>equals</code> and <code>hashCode</code> are declared for the benefit of hashtables such as <code>java.util.Hashtable</code> <a href="javautil.doc7.html#7569">(&#167;21.7)</a>. The method <code>equals</code> defines a notion of object equality, which is based on value, not reference, comparison.
<a name="12115"></a>
<li>The method <code>clone</code> is used to make a duplicate of an object.
<a name="12116"></a>
<li>The methods <code>wait</code>, <code>notify</code>, and <code>notifyAll</code> are used in concurrent programming using threads, as described in <a href="17.doc.html#26250">&#167;17</a>.
<a name="12117"></a>
<li>The method <code>finalize</code> is run just before an object is destroyed and is described in <a href="12.doc.html#44748">&#167;12.6</a>.
</ul><a name="26992"></a>
<h3>4.3.3    The Class <code>String</code></h3>
<a name="27000"></a>
Instances of class <code>String</code> <a href="javalang.doc11.html#14460">(&#167;20.12)</a> represent sequences of Unicode characters. 
A &#32;<code>String</code> object has a constant (unchanging) value. String literals <a href="3.doc.html#101083">(&#167;3.10.5)</a> are 
references to instances of class <code>String</code>.
<p><a name="52188"></a>
The string concatenation operator <code>+</code> <a href="15.doc.html#39990">(&#167;15.17.1)</a> implicitly creates a new <code>String</code> object.<p>
<a name="52197"></a>
<h3>4.3.4    When Reference Types Are the Same</h3>
<a name="22319"></a>
Two reference types the <i>same type</i> if:
<p><ul><a name="86567"></a>
<li>They are both class or both interface types, are loaded by the same class loader, and have the same fully-qualified name <a href="6.doc.html#33916">(&#167;6.6)</a>, in which case they are sometimes said to be the <i>same class</i> or the <i>same interface</i>.
<a name="86576"></a>
<li>They are both array types, and have the same component type <a href="10.doc.html#27803">(&#167;10)</a>.
</ul><a name="25948"></a>
<h2>4.4    Where Types Are Used</h2>
<a name="52309"></a>
Types are used when they appear in declarations or in certain expressions.
<p><a name="85893"></a>
The following code fragment contains one or more instances of each kind of usage of a type:<p>
<pre><br><a name="52319"></a>import java.util.Random;
<br></pre><pre><a name="52320"></a>
class MiscMath {
<br><a name="19644"></a>	int divisor;
<br><a name="85892"></a>
	MiscMath(int divisor) {
<a name="85931"></a>		this.divisor = divisor;
<a name="85932"></a>	}
<br><a name="19646"></a>
	float ratio(long l) {
<a name="52325"></a>		try {
<a name="52326"></a>			l /= divisor;
<a name="52327"></a>		} catch (Exception e) {
<a name="52328"></a>			if (e instanceof ArithmeticException)
<a name="52329"></a>				l = Long.MAX_VALUE;
<a name="52330"></a>			else
<a name="52331"></a>				l = 0;
<a name="52332"></a>		}
<a name="52333"></a>		return (float)l;
<a name="52334"></a>	}
<br><a name="19664"></a>
	double gausser() {
<a name="19665"></a>		Random r = new Random();
<a name="19666"></a>		double[] val = new double[2];
<a name="19667"></a>		val[0] = r.nextGaussian();
<a name="19668"></a>		val[1] = r.nextGaussian();
<a name="19669"></a>		return (val[0] + val[1]) / 2;
<a name="19670"></a>	}
<br><a name="52342"></a>}
</pre><a name="53860"></a>
In this example, types are used in declarations of the following:
<p><ul><a name="53864"></a>
<li>Imported types <a href="7.doc.html#26656">(&#167;7.5)</a>; here the type <code>Random</code>, imported from the type<code> java.util.Random</code> of the package <code>java.util</code>, is declared
<a name="49983"></a>
<li>Fields, which are the class variables and instance variables of classes <a href="8.doc.html#40898">(&#167;8.3)</a>, and constants of interfaces <a href="9.doc.html#78642">(&#167;9.3)</a>; here the field <code>divisor</code> in the class <code>MiscMath</code> &#32;is declared to be of type <code>int</code>
<a name="49990"></a>
<li>Method parameters <a href="8.doc.html#38698">(&#167;8.4.1)</a>; here the parameter <code>l</code> of the method <code>ratio</code> is declared to be of type <code>long</code>
<a name="52378"></a>
<li>Method results <a href="8.doc.html#40420">(&#167;8.4)</a>; here the result of the method <code>ratio</code> is declared to be of type <code>float</code>, and the result of the method <code>gausser</code> is declared to be of type <code>double</code>
<a name="38145"></a>
<li>Constructor parameters <a href="8.doc.html#29488">(&#167;8.6.1)</a>; here the parameter of the constructor for<code> MiscMath</code> is declared to be of type <code>int</code>
<a name="12250"></a>
<li>Local variables (<a href="14.doc.html#5920">&#167;14.3</a>, <a href="14.doc.html#24588">&#167;14.12</a>); the local variables <code>r</code> and <code>val</code> of the method <code>gausser</code> are declared to be of types <code>Random</code> and <code>double[]</code> (array of <code>double</code>)
<a name="52411"></a>
<li>Exception handler parameters <a href="14.doc.html#79311">(&#167;14.18)</a>; here the exception handler parameter <code>e</code> of the <code>catch</code> clause is declared to be of type <code>Exception</code>
</ul><a name="25979"></a>
and in expressions of the following kinds:
<p><ul><a name="52468"></a>
<li>Class instance creations <a href="15.doc.html#41147">(&#167;15.8)</a>; here a local variable <code>r</code> of method <code>gausser</code> is initialized by a class instance creation expression that uses the type <code>Random</code>
<a name="87680"></a>
<li>Array creations <a href="15.doc.html#46168">(&#167;15.9)</a>; here the local variable <code>val</code> of method <code>gausser</code> is initialized by an array creation expression that creates an array of <code>double</code> with size 2
<a name="52427"></a>
<li>Casts <a href="15.doc.html#238146">(&#167;15.15)</a>; here the <code>return</code> statement of the method <code>ratio</code> uses the <code>float</code> type in a cast
<a name="25987"></a>
<li>The <code>instanceof</code> operator <a href="15.doc.html#80289">(&#167;15.19.2)</a>; here the <code>instanceof</code> operator tests whether <code>e</code> is assignment compatible with the type <code>ArithmeticException</code>
</ul><a name="18470"></a>
<h2>4.5    Variables</h2>
<a name="10872"></a>
A variable is a storage location and has an associated type, sometimes called its 
<i>compile-time type</i>, that is either a primitive type <a href="4.doc.html#85587">(&#167;4.2)</a> or a reference type <a href="4.doc.html#9317">(&#167;4.3)</a>. 
A variable always contains a value that is assignment compatible <a href="5.doc.html#170768">(&#167;5.2)</a> with its 
type. A variable's value is changed by an assignment <a href="15.doc.html#5281">(&#167;15.25)</a> or by a prefix or 
postfix <code>++</code> (increment) or <code>--</code> (decrement) operator (<a href="15.doc.html#39438">&#167;15.13.2</a>, <a href="15.doc.html#4987">&#167;15.13.3</a>, <a href="15.doc.html#39547">&#167;15.14.1</a>, 
<a href="15.doc.html#239136">&#167;15.14.2</a>).
<p><a name="24555"></a>
Compatibility of the value of a variable with its type is guaranteed by the design of the Java language. Default values are compatible <a href="4.doc.html#10931">(&#167;4.5.4)</a> and all assignments to a variable are checked for assignment compatibility <a href="5.doc.html#170768">(&#167;5.2)</a>, usually at compile time, but, in a single case involving arrays, a run-time check is made <a href="10.doc.html#11430">(&#167;10.10)</a>.<p>
<a name="28344"></a>
<h3>4.5.1    Variables of Primitive Type</h3>
<a name="17088"></a>
A variable of a primitive type always holds a value of that exact primitive type.
<p><a name="28345"></a>
<h3>4.5.2    Variables of Reference Type</h3>
<a name="10877"></a>
A variable of reference type can hold either of the following:
<p><ul><a name="52494"></a>
<li>A null reference
<a name="52496"></a>
<li>A reference to any object <a href="4.doc.html#9317">(&#167;4.3)</a> whose class <a href="4.doc.html#24887">(&#167;4.5.5)</a> is assignment compatible <a href="5.doc.html#170768">(&#167;5.2)</a> with the type of the variable
</ul><a name="28536"></a>
<h3>4.5.3    Kinds of Variables</h3>
<a name="10883"></a>
There are seven kinds of variables:
<p><ol>
<a name="10884"></a>
<li>A <i>class variable</i> is a field declared using the keyword <code>static</code> within a class declaration <a href="8.doc.html#37544">(&#167;8.3.1.1)</a>, or with or without the keyword <code>static</code> within an interface declaration <a href="9.doc.html#78642">(&#167;9.3)</a>. A class variable is created when its class or interface is loaded <a href="12.doc.html#44459">(&#167;12.2)</a> and is initialized to a default value <a href="4.doc.html#10931">(&#167;4.5.4)</a>. The class variable effectively ceases to exist when its class or interface is unloaded <a href="12.doc.html#44850">(&#167;12.8)</a>, after any necessary finalization of the class or interface <a href="12.doc.html#44748">(&#167;12.6)</a> has been completed.
<a name="51516"></a>
<li>An <i>instance variable</i> is a field declared within a class declaration without using the keyword <code>static</code> <a href="8.doc.html#37544">(&#167;8.3.1.1)</a>. If a class <code>T</code> has a field <i>a</i> that is an instance variable, then a new instance variable <i>a</i> is created and initialized to a default value <a href="4.doc.html#10931">(&#167;4.5.4)</a> as part of each newly created object of class <code>T</code> or of any class that is a subclass of <code>T</code> <a href="8.doc.html#21723">(&#167;8.1.3)</a>. The instance variable effectively ceases to exist when the object of which it is a field is no longer referenced, after any necessary finalization of the object <a href="12.doc.html#44748">(&#167;12.6)</a> has been completed.
<a name="10895"></a>
<li><i>Array components</i> are unnamed variables that are created and initialized to default values <a href="4.doc.html#10931">(&#167;4.5.4)</a> whenever a new object that is an array is created <a href="15.doc.html#46168">(&#167;15.9)</a>. The array components effectively cease to exist when the array is no longer referenced. See <a href="10.doc.html#27803">&#167;10</a> for a description of arrays.
<a name="24632"></a>
<li><i>Method parameters</i> <a href="8.doc.html#38698">(&#167;8.4.1)</a> name argument values passed to a method. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked <a href="15.doc.html#20448">(&#167;15.11)</a>. The new variable is initialized with the corresponding argument value from the method invocation. The method parameter effectively ceases to exist when the execution of the body of the method is complete.
<a name="24657"></a>
<li><i>Constructor parameters</i> <a href="8.doc.html#29488">(&#167;8.6.1)</a> name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression <a href="15.doc.html#41147">(&#167;15.8)</a> or explicit constructor invocation <a href="8.doc.html#78435">(&#167;8.6.5)</a> invokes that constructor. The new variable is initialized with the corresponding argument value from the creation expression or constructor invocation. The constructor parameter effectively ceases to exist when the execution of the body of the constructor is complete.
<a name="10903"></a>
<li>An <i>exception-handler parameter</i> is created each time an exception is caught by a <code>catch</code> clause of a <code>try</code> statement <a href="14.doc.html#79311">(&#167;14.18)</a>. The new variable is initialized with the actual object associated with the exception (<a href="11.doc.html#44153">&#167;11.3</a>, <a href="14.doc.html#237350">&#167;14.16</a>). The exception-handler parameter effectively ceases to exist when execution of the block associated with the <code>catch</code> clause is complete.
<a name="24801"></a>
<li><i>Local variables</i> are declared by local variable declaration statements <a href="14.doc.html#5920">(&#167;14.3)</a>. Whenever the flow of control enters a block <a href="14.doc.html#24644">(&#167;14.2)</a> or <code>for</code> statement <a href="14.doc.html#24588">(&#167;14.12)</a>, a new variable is created for each local variable declared in a local variable declaration statement immediately contained within that block or <code>for</code> statement. A local variable declaration statement may contain an expression which initializes the variable. The local variable with an initializing expression is not initialized, however, until the local variable declaration statement that declares it is executed. (The rules of definite assignment <a href="16.doc.html#25979">(&#167;16)</a> prevent the value of a local variable from being used before it has been initialized or otherwise assigned a value.) The local variable effectively ceases to exist when the execution of the block or <code>for</code> statement is complete.
</ol>
<ul><a name="24816"></a>
<br><br>Were it not for one exceptional situation, a local variable could always be regarded as being created when its local variable declaration statement is executed. The exceptional situation involves the <code>switch</code> statement <a href="14.doc.html#35518">(&#167;14.9)</a>, where it is possible for control to enter a block but bypass execution of a local variable declaration statement. Because of the restrictions imposed by the rules of definite assignment <a href="16.doc.html#">(&#167;16)</a>, however, the local variable declared by such a bypassed local variable declaration statement cannot be used before it has been definitely assigned a value by an assignment expression <a href="15.doc.html#5281">(&#167;15.25)</a>.
</ul><a name="24836"></a>
The following example contains several different kinds of variables:<p>
<pre><a name="10918"></a>
class Point {
<a name="45636"></a>	static int numPoints;								// numPoints is a class variable
<a name="50087"></a>	int x, y;								// x and y are instance variables
<a name="50089"></a>	int[] w = new int[10];								// w[0] is an array component
<a name="52523"></a>	int setX(int x) {								// x is a method parameter
<a name="52524"></a>		int oldx = this.x;							// oldx is a local variable
<a name="10925"></a>		this.x = x;
<a name="10926"></a>		return oldx;
<a name="10927"></a>	}
<a name="10928"></a>}
</pre><a name="10931"></a>
<h3>4.5.4    Initial Values of Variables</h3>
<a name="10935"></a>
Every variable in a Java program must have a value before its value is used:
<p><ul><a name="10946"></a>
<li>Each class variable, instance variable, or array component is initialized with a <i>default value</i> when it is created (<a href="15.doc.html#41147">&#167;15.8</a>, <a href="15.doc.html#46168">&#167;15.9</a>, <a href="javalang.doc2.html#15088">&#167;20.3.6</a>):
<ul>
<a name="10947"></a>
<li>For type <code>byte</code>, the default value is zero, that is, the value of <code>(byte)0</code>.
<a name="10948"></a>
<li>For type <code>short</code>, the default value is zero, that is, the value of <code>(short)0</code>.
<a name="10949"></a>
<li>For type <code>int</code>, the default value is zero, that is, <code>0</code>.
<a name="10950"></a>
<li>For type <code>long</code>, the default value is zero, that is, <code>0L</code>.
<a name="10951"></a>
<li>For type <code>float</code>, the default value is positive zero, that is, <code>0.0f</code>.
<a name="46977"></a>
<li>For type <code>double</code>, the default value is positive zero, that is, <code>0.0d</code>.
<a name="46978"></a>
<li>For type <code>char</code>, the default value is the null character, that is, '<code>\u0000</code>'.
<a name="46979"></a>
<li>For type <code>boolean</code>, the default value is <code>false</code>.
<a name="10955"></a>
<li>For all reference types <a href="4.doc.html#9317">(&#167;4.3)</a>, the default value is <code>null</code>.
</ul>
<a name="11353"></a>
<li>Each method parameter <a href="8.doc.html#38698">(&#167;8.4.1)</a> is initialized to the corresponding argument value provided by the invoker of the method <a href="15.doc.html#20448">(&#167;15.11)</a>.
<a name="38160"></a>
<li>Each constructor parameter <a href="8.doc.html#29488">(&#167;8.6.1)</a> is initialized to the corresponding argument value provided by a class instance creation expression <a href="15.doc.html#41147">(&#167;15.8)</a> or explicit constructor invocation <a href="8.doc.html#78435">(&#167;8.6.5)</a>.
<a name="11354"></a>
<li>An exception-handler parameter <a href="14.doc.html#79311">(&#167;14.18)</a> is initialized to the thrown object representing the exception (<a href="11.doc.html#44153">&#167;11.3</a>, <a href="14.doc.html#237350">&#167;14.16</a>). 
<a name="11569"></a>
<li>A local variable (<a href="14.doc.html#5920">&#167;14.3</a>, <a href="14.doc.html#24588">&#167;14.12</a>) must be explicitly given a value before it is used, by either initialization <a href="14.doc.html#5920">(&#167;14.3)</a> or assignment <a href="15.doc.html#5281">(&#167;15.25)</a>, in a way that can be verified by the compiler using the rules for definite assignment <a href="16.doc.html#25979">(&#167;16)</a>.
</ul><a name="30962"></a>
The example program:
<p><pre><a name="30963"></a>
class Point {
<a name="12302"></a>	static int npoints;
<a name="12303"></a>	int x, y;
<a name="12309"></a>	Point root;
<a name="12307"></a>}
<br><a name="12308"></a>
class Test {
<a name="12310"></a>	public static void main(String[] args) {
<a name="50091"></a>		System.out.println("npoints=" + Point.npoints);
<a name="12326"></a>		Point p = new Point();
<a name="12327"></a>		System.out.println("p.x=" + p.x + ", p.y=" + p.y);
<a name="12328"></a>		System.out.println("p.root=" + p.root);
<a name="12332"></a>	}
<a name="12329"></a>}
</pre><a name="12324"></a>
prints:
<p><pre><a name="12336"></a>
npoints=0
<a name="12337"></a>p.x=0, p.y=0
<a name="12325"></a>p.root=null
</pre><a name="24882"></a>
illustrating the default initialization of <code>npoints</code>, which occurs when the class 
<code>Point</code> is prepared <a href="12.doc.html#47979">(&#167;12.3.2)</a>, and the default initialization of <code>x</code>, <code>y</code>, and <code>root</code>, which 
occurs when a new <code>Point</code> is instantiated. See <a href="12.doc.html#44410">&#167;12</a> for a full description of all 
aspects of loading, linking, and initialization of classes and interfaces, plus a 
description of the instantiation of classes to make new class instances.
<p><a name="24887"></a>
<h3>4.5.5    Variables Have Types, Objects Have Classes</h3>
<a name="24888"></a>
Every object belongs to some particular class: the class that was mentioned in the 
creation expression that produced the object, the class whose class object was 
used to invoke the <code>newInstance</code> method <a href="javalang.doc2.html#15088">(&#167;20.3.6)</a> to produce the object, or the 
<code>String</code> class for objects implicitly created by the string concatenation operator <code>+ 
</code><a href="15.doc.html#39990">(&#167;15.17.1)</a>. This class is called the <i>class of the object</i>. (Arrays also have a class, as 
described at the end of this section.) An object is said to be an instance of its class 
and of all superclasses of its class.
<p><a name="24900"></a>
(Sometimes a variable or expression is said to have a "run-time type" but that is an abuse of terminology; it refers to the class of the object referred to by the value of the variable or expression at run time, assuming that the value is not <code>null</code>. Properly speaking, type is a compile-time notion. A variable or expression has a type; an object or array has no type, but belongs to a class.)<p>
<a name="24901"></a>
The type of a variable is always declared, and the type of an expression can be deduced at compile time. The type limits the possible values that the variable can hold or the expression can produce at run time. If a run-time value is a reference that is not <code>null</code>, it refers to an object or array that has a class (not a type), and that class will necessarily be compatible with the compile-time type.<p>
<a name="24895"></a>
Even though a variable or expression may have a compile-time type that is an interface type, there are no instances of interfaces. A variable or expression whose type is an interface type can reference any object whose class implements <a href="8.doc.html#34031">(&#167;8.1.4)</a> that interface.<p>
<a name="24918"></a>
Here is an example of creating new objects and of the distinction between the type of a variable and the class of an object:<p>
<pre><a name="52597"></a>
public interface Colorable {
<a name="24921"></a>	void setColor(byte r, byte g, byte b);
<a name="24922"></a>}
<br><a name="52598"></a>class Point { int x, y; }
<a name="52599"></a>
class ColoredPoint extends Point implements Colorable {
<br><a name="52600"></a>	byte r, g, b;
<br><a name="52601"></a>
	public void setColor(byte rv, byte gv, byte bv) {
<a name="23360"></a>		r = rv; g = gv; b = bv;
<a name="23361"></a>	}
<br><a name="52604"></a>}
<br><a name="52605"></a>
class Test {
<a name="52606"></a>	public static void main(String[] args) {
<a name="52607"></a>		Point p = new Point();
<a name="52608"></a>		ColoredPoint cp = new ColoredPoint();
<a name="52609"></a>		p = cp;
<a name="52610"></a>		Colorable c = cp;
<a name="23366"></a>	}
<a name="52611"></a>}
</pre><a name="52612"></a>
In this example:
<p><ul><a name="52613"></a>
<li>The local variable <code>p</code> of the method <code>main</code> of class <code>Test</code> has type <code>Point</code> and is initially assigned a reference to a new instance of class <code>Point</code>.
<a name="52614"></a>
<li>The local variable <code>cp</code> similarly has as its type <code>ColoredPoint</code>, and is initially assigned a reference to a new instance of class <code>ColoredPoint</code>.
<a name="52615"></a>
<li>The assignment of the value of <code>cp</code> to the variable <code>p</code> causes <code>p</code> to hold a reference to a <code>ColoredPoint</code> object. This is permitted because <code>ColoredPoint</code> is a subclass of <code>Point</code>, so the class <code>ColoredPoint</code> is assignment compatible <a href="5.doc.html#170768">(&#167;5.2)</a> with the type <code>Point</code>. A <code>ColoredPoint</code> object includes support for all the methods of a <code>Point</code>. In addition to its particular fields <code>r</code>, <code>g</code>, and <code>b</code>, it has the fields of class <code>Point</code>, namely <code>x</code> and <code>y</code>.
<a name="52586"></a>
<li>The local variable <code>c</code> has as its type the interface type <code>Colorable</code>, so it can hold a reference to any object whose class implements <code>Colorable</code>; specifically, it can hold a reference to a <code>ColoredPoint</code>.
<a name="24972"></a>
<li>Note that an expression such as "<code>new Colorable()</code>" is not valid because it is not possible to create an instance of an interface, only of a class.
</ul><a name="24976"></a>
Every array also has a class; the method <code>getClass</code> <a href="javalang.doc1.html#13783">(&#167;20.1.1)</a>, when invoked for an array object, will return a class object (of class <code>Class</code>) that represents the class of the array. The classes for arrays have strange names that are not valid Java identifiers; for example, the class for an array of <code>int</code> components has the name "<code>[I</code>" and so the value of the expression:<p>
<pre><a name="24985"></a>new int[10].getClass().getName()
</pre><a name="85679"></a>
is the string <code>"[I"</code>; see <a href="javalang.doc1.html#13783">&#167;20.1.1</a> for details.
<p>

<hr>
<!-- This inserts footnotes-->
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="3.doc.html">Prev</a> | <a href="5.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<p>
<font size=-1>Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)<br>
<i><a href="jcopyright.doc.html">Copyright &#169 1996 Sun Microsystems, Inc.</a>
All rights reserved</i>
<br>
Please send any comments or corrections via our <a href="http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback">feedback form</a>
</font>
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body></html><html>
<head>
<meta name="collection" content="exclude">

<title>The Java Language Specification
 Names</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
 
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="5.doc.html">Prev</a> | <a href="7.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<hr><br>
 
<a name="48086"></a>
<p><strong>
CHAPTER
 6 </strong></p>
<a name="44352"></a>
<h1>Names</h1>
<hr><p>
<a name="10551"></a>
Names are used to refer to entities declared in a Java program. A declared 
entity <a href="6.doc.html#33757">(&#167;6.1)</a> is a package, class type, interface type, member (field or method) of a 
reference type, parameter (to a method, constructor, or exception handler), or 
local variable.
<p><a name="56343"></a>
Names in Java programs are either simple, consisting of a single identifier, or qualified, &#32;consisting of a sequence of identifiers separated by "<code>.</code>" tokens <a href="6.doc.html#31692">(&#167;6.2)</a>.<p>
<a name="56234"></a>
Every name introduced by a declaration has a <i>scope</i> <a href="6.doc.html#33623">(&#167;6.3)</a>, which is the part of the Java program text within which the declared entity can be referred to by a simple name.<p>
<a name="56241"></a>
Packages and reference types (that is, class types, interface types, and array types) have members <a href="6.doc.html#31814">(&#167;6.4)</a>. A member can be referred to using a qualified name <i>N</i><code>.</code><i>x</i>, where <i>N</i> is a simple or qualified name and <i>x</i> is an identifier. If <i>N</i> names a package, then <i>x</i> is a member of that package, which is either a class or interface type or a subpackage. If <i>N</i> names a reference type or a variable of a reference type, then <i>x</i> names a member of that type, which is either a field or a method.<p>
<a name="34249"></a>
In determining the meaning of a name <a href="6.doc.html#20569">(&#167;6.5)</a>, Java uses the context of the occurrence to disambiguate among packages, types, variables, and methods with the same name.<p>
<a name="56266"></a>
Access control <a href="6.doc.html#33916">(&#167;6.6)</a> can be specified in a class, interface, method, or field declaration to control when <i>access</i> to a member is allowed. Access is a different concept from scope; access specifies the part of the Java program text within which the declared entity can be referred to by a qualified name, a field access expression <a href="15.doc.html#41267">(&#167;15.10)</a>, or a method invocation expression <a href="15.doc.html#20448">(&#167;15.11)</a> in which the method is not specified by a simple name. The default access is that a member can be accessed anywhere within the package that contains its declaration; other possibilities are <code>public</code>, <code>protected</code>, and <code>private</code>.<p>
<a name="27329"></a>
Fully qualified names <a href="6.doc.html#25430">(&#167;6.7)</a> and naming conventions <a href="6.doc.html#11186">(&#167;6.8)</a> are also discussed in this chapter.<p>
<a name="31249"></a>
The name of a field, parameter, or local variable may be used as an expression <a href="15.doc.html#4984">(&#167;15.13.1)</a>. The name of a method may appear in an expression only as part of a method invocation expression <a href="15.doc.html#20448">(&#167;15.11)</a>. The name of a class or interface type may appear in an expression only as part of a class instance creation expression <a href="15.doc.html#41147">(&#167;15.8)</a>, an array creation expression <a href="15.doc.html#46168">(&#167;15.9)</a>, a cast expression <a href="15.doc.html#238146">(&#167;15.15)</a>, or an <code>instanceof</code> expression <a href="15.doc.html#80289">(&#167;15.19.2)</a>, or as part of a qualified name for a field or method. The name of a package may appear in an expression only as part of a qualified name for a class or interface type.<p>
<a name="33757"></a>
<h2>6.1    Declarations</h2>
<a name="33759"></a>
A <i>declaration</i> introduces an entity into a Java program and includes an identifier 
<a href="3.doc.html#40625">(&#167;3.8)</a> that can be used in a name to refer to this entity. A declared entity is one of 
the following:
<p><ul><a name="60314"></a>
<li>A package, declared in a <code>package</code> declaration <a href="7.doc.html#26619">(&#167;7.4)</a>
<a name="60319"></a>
<li>An imported type, declared in a single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> or a type-import-on-demand declaration <a href="7.doc.html#26725">(&#167;7.5.2)</a>
<a name="27103"></a>
<li>A class, declared in a class type declaration <a href="8.doc.html#15372">(&#167;8.1)</a>
<a name="27107"></a>
<li>An interface, declared in an interface type declaration <a href="9.doc.html#35470">(&#167;9.1)</a>
<a name="27117"></a>
<li>A member of a reference type (<a href="8.doc.html#21831">&#167;8.2</a>, <a href="9.doc.html#32392">&#167;9.2</a>, <a href="10.doc.html#11364">&#167;10.7</a>), one of the following:
<ul>
<a name="20164"></a>
<li>A field, one of the following:
<ul>
<a name="20168"></a>
<li>A field declared in a class type <a href="8.doc.html#40898">(&#167;8.3)</a>
<a name="20172"></a>
<li>A constant field declared in an interface type <a href="9.doc.html#78642">(&#167;9.3)</a>
<a name="20173"></a>
<li>The field <code>length</code>, which is implicitly a member of every array type <a href="10.doc.html#11364">(&#167;10.7)</a>
</ul>
<a name="33764"></a>
<li>A method, one of the following:
<ul>
<a name="38090"></a>
<li>A method (<code>abstract</code> or otherwise) declared in a class type <a href="8.doc.html#40420">(&#167;8.4)</a>
<a name="33944"></a>
<li>A method (always <code>abstract</code>) declared in an interface type <a href="9.doc.html#78651">(&#167;9.4)</a>
</ul>
</ul>
</ul><ul><a name="31380"></a>
<li>A parameter, one of the following:
<ul>
<a name="33773"></a>
<li>A parameter of a method or constructor of a class (<a href="8.doc.html#38698">&#167;8.4.1</a>, <a href="8.doc.html#29488">&#167;8.6.1</a>)
<a name="33775"></a>
<li>A parameter of an <code>abstract</code> method of an interface <a href="9.doc.html#78651">(&#167;9.4)</a>
<a name="31398"></a>
<li>A parameter of an exception handler declared in a <code>catch</code> clause of a <code>try</code> statement <a href="14.doc.html#79311">(&#167;14.18)</a>
</ul>
<a name="31392"></a>
<li>A local variable, one of the following:
<ul>
<a name="33776"></a>
<li>A local variable declared in a block <a href="14.doc.html#5920">(&#167;14.3)</a>
<a name="33777"></a>
<li>A local variable declared in a <code>for</code> statement <a href="14.doc.html#24588">(&#167;14.12)</a>
</ul>
</ul><a name="56358"></a>
Constructors <a href="8.doc.html#41652">(&#167;8.6)</a> are also introduced by declarations, but use the name of the 
class in which they are declared rather than introducing a new name.
<p><a name="31692"></a>
<h2>6.2    Names and Identifiers</h2>
<a name="61760"></a>
A <i>name</i> is used to refer to an entity declared in a Java program.
<p><a name="61763"></a>
There are two forms of names: simple names and qualified names. A <i>simple name</i> is a single identifier. A <i>qualified name</i> consists of a name, a "<code>.</code>" token, and an identifier.<p>
<a name="21637"></a>
In determining the meaning of a name <a href="6.doc.html#20569">(&#167;6.5)</a>, the Java language takes into account the context in which the name appears. It distinguishes among contexts where a name must denote (refer to) a package <a href="6.doc.html#22349">(&#167;6.5.3)</a>, a type <a href="6.doc.html#21721">(&#167;6.5.4)</a>, a variable or value in an expression <a href="6.doc.html#21650">(&#167;6.5.5)</a>, or a method <a href="6.doc.html#21652">(&#167;6.5.6)</a>.<p>
<a name="33483"></a>
Not all identifiers in Java programs are a part of a name. Identifiers are also used in the following situations:<p>
<ul><a name="33485"></a>
<li>In declarations <a href="6.doc.html#33757">(&#167;6.1)</a>, where an identifier may occur to specify the name by which the declared entity will be known
<a name="33490"></a>
<li>In field access expressions <a href="15.doc.html#41267">(&#167;15.10)</a>, where an identifier occurs after a "<code>.</code>" token to indicate a member of an object that is the value of an expression or the keyword <code>super</code> that appears before the "<code>.</code>" token
<a name="33491"></a>
<li>In some method invocation expressions <a href="15.doc.html#20448">(&#167;15.11)</a>, where an identifier may occur after a "<code>.</code>" token and before a "<code>(</code>" token to indicate a method to be invoked for an object that is the value of an expression or the keyword <code>super</code> that appears before the "<code>.</code>" token
<a name="33492"></a>
<li>As labels in labeled statements <a href="14.doc.html#78993">(&#167;14.6)</a> and in <code>break</code> <a href="14.doc.html#6842">(&#167;14.13)</a> and <code>continue</code> <a href="14.doc.html#6122">(&#167;14.14)</a> statements that refer to statement labels
</ul><a name="38317"></a>
In the example:
<p><pre><a name="38318"></a>
class Test {
<a name="38319"></a>	public static void main(String[] args) {
<a name="31441"></a>		Class c = System.out.getClass();
<a name="38320"></a>		System.out.println(c.toString().length() +
<a name="31466"></a>								args[0].length() + args.length);
<a name="38324"></a>	}
<a name="38325"></a>}
</pre><a name="61602"></a>
the identifiers <code>Test</code>, <code>main</code>, and the first occurrences of <code>args</code> and <code>c</code> are not names; 
rather, they are used in declarations to specify the names of the declared entities. 
The names <code>String</code>, <code>Class</code>, <code>System.out.getClass,</code> <code>System.out.println</code>, 
<code>c.toString</code>, <code>args</code>, and <code>args.length</code> appear in the example. The first occurrence
of <code>length</code> is not a name, but rather an identifier appearing in a method invocation
expression <a href="15.doc.html#20448">(&#167;15.11)</a>. The second occurrence of <code>length</code> is not a name, but 
rather an identifier appearing in a method invocation expression <a href="15.doc.html#20448">(&#167;15.11)</a>.
<p><a name="61609"></a>
The identifiers used in labeled statements and their associated <code>break</code> and <code>continue</code> statements are completely separate from those used in declarations. Thus, the following code is valid:<p>
<pre><a name="38178"></a>
class TestString {
<br><a name="38277"></a>	char[] value;
<br><br><a name="38278"></a>	int offset, count;
<br><a name="38262"></a>	int indexOf(TestString str, int fromIndex) {
<a name="38179"></a>		char[] v1 = value, v2 = str.value;
<a name="38309"></a>		int max = offset + (count - str.count);
<a name="31499"></a>		int start = offset + ((fromIndex &lt; 0) ? 0 : fromIndex);
<a name="38310"></a>	i:
<a name="38312"></a>		for (int i = start; i &lt;= max; i++)<br>
		{
<a name="38184"></a>			int n = str.count, j = i, k = str.offset;
<a name="38187"></a>			while (n-- != 0) {
<a name="38188"></a>				if (v1[j++] != v2[k++])
<a name="38189"></a>					continue i;
<a name="38191"></a>			} 
<a name="38241"></a>			return i - offset;
<a name="38251"></a>		}
<a name="38194"></a>		return -1;
<a name="38266"></a>	}
<a name="38274"></a>}
</pre><a name="54045"></a>
This code was taken from a version of the class <code>String</code> and its method <code>indexOf</code> 
<a href="javalang.doc11.html#30903">(&#167;20.12.26)</a>, where the label was originally called <code>test</code>. Changing the label to 
have the same name as the local variable <code>i</code> does not hide the label in the scope of 
the declaration of <code>i</code>. The identifier <code>max</code> could also have been used as the statement 
label; the label would not hide the local variable <code>max</code> within the labeled statement.
<p><a name="33623"></a>
<h2>6.3    Scope of a Simple Name</h2>
<a name="34028"></a>
The <i>scope</i> of a declaration is the region of the program within which the entity 
declared by the declaration can be referred to using a simple name:
<p><ul><a name="56405"></a>
<li>The scope of a package, as introduced by a <code>package</code> declaration, is determined by the host system <a href="7.doc.html#13180">(&#167;7.4.3)</a>. All Java code is within the scope of the standard package named <code>java</code>, so the package <code>java</code> can always be referred to by Java code.
<a name="31532"></a>
<li>The scope of a type imported by a single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> or type-import-on-demand declaration <a href="7.doc.html#26725">(&#167;7.5.2)</a> is all the class and interface type declarations <a href="7.doc.html#26783">(&#167;7.6)</a> in the compilation unit in which the import declaration appears.
<a name="56422"></a>
<li>The scope of a type introduced by a class type declaration <a href="8.doc.html#39196">(&#167;8.1.1)</a> or interface type declaration <a href="9.doc.html#39713">(&#167;9.1.1)</a> is the declarations of all class and interface types in all the compilation units <a href="7.doc.html#40031">(&#167;7.3)</a> of the package in which it is declared.
<a name="19824"></a>
<li>The scope of a member declared in or inherited by a class type <a href="8.doc.html#21831">(&#167;8.2)</a> or interface type <a href="9.doc.html#32392">(&#167;9.2)</a> is the entire declaration of the class or interface type. The declaration of a member needs to appear before it is used only when the use is in a field initialization expression (<a href="8.doc.html#24510">&#167;8.3.2</a>, <a href="12.doc.html#44630">&#167;12.4.2</a>, <a href="12.doc.html#44670">&#167;12.5</a>). This means that a compile-time error results from the test program:
</ul><pre><a name="19834"></a>
	class Test {
<a name="19835"></a>		int i = j;				// compile-time error: incorrect forward reference
<a name="19836"></a>		int j = 1;
<a name="19837"></a>	}
</pre><ul><a name="19838"></a>
<br><br>whereas the following example compiles without error:
</ul><pre><a name="19839"></a>
	class Test {
<a name="19840"></a>		Test() { k = 2; }
<a name="19841"></a>		int j = 1;
<a name="19842"></a>		int i = j;
<a name="19843"></a>		int k;
<a name="19844"></a>	}
</pre><ul><a name="19848"></a>
<br><br>even though the constructor <a href="8.doc.html#41652">(&#167;8.6)</a> for <code>Test</code> refers to the field <code>k</code> that is declared three lines later.
</ul><ul><a name="31556"></a>
<li>The scope of a parameter of a method <a href="8.doc.html#38698">(&#167;8.4.1)</a> is the entire body of the method.
</ul><ul><a name="31566"></a>
<li>The scope of a parameter of a constructor <a href="8.doc.html#29488">(&#167;8.6.1)</a> is the entire body of the constructor.
<a name="19941"></a>
<li>The scope of a local variable declaration in a block <a href="14.doc.html#32644">(&#167;14.3.2)</a> is the rest of the block in which the declaration appears, starting with its own initializer <a href="14.doc.html#5920">(&#167;14.3)</a> and including any further declarators to the right in the local variable declaration statement.
<a name="56450"></a>
<li>The scope of a local variable declared in the <i>ForInit</i> part of a <code>for</code> statement <a href="14.doc.html#24588">(&#167;14.12)</a> includes all of the following:
<ul>
<a name="23092"></a>
<li>Its own initializer
<a name="56451"></a>
<li>Any further declarators to the right in the <i>ForInit</i> part of the <code>for</code> statement
<a name="56452"></a>
<li>The <i>Expression</i> and <i>ForUpdate</i> parts of the <code>for</code> statement
<a name="56453"></a>
<li>The contained <i>Statement</i>
</ul>
<a name="56454"></a>
<li>The scope of a parameter of an exception handler that is declared in a <code>catch</code> clause of a <code>try</code> statement <a href="14.doc.html#79311">(&#167;14.18)</a> is the entire block associated with the <code>catch</code>.
</ul><a name="56458"></a>
These rules imply that declarations of class and interface types need not appear 
before uses of the types.
<p><a name="20278"></a>
In the example:<p>
<pre><a name="56459"></a>package points;
</pre><pre><a name="56460"></a>
class Point {
<a name="56461"></a>	int x, y;
<a name="56462"></a>	PointList list;
<a name="56463"></a>	Point next;
<a name="56464"></a>}
<a name="56465"></a>
class PointList {
<a name="56466"></a>	Point first;
<a name="56468"></a>}
</pre><a name="34047"></a>
the use of <code>PointList</code> in class <code>Point</code> is correct, because the scope of the class type 
name <code>PointList</code> includes both class <code>Point</code> and class <code>PointList</code>, as well as any 
other type declarations in other compilation units of package <code>points</code>.
<p><a name="34133"></a>
<h3>6.3.1    Hiding Names</h3>
<a name="34051"></a>
Some declarations may be hidden <a href="6.doc.html#34133">(&#167;6.3.1)</a> in part of their scope by another declaration
of the same name, in which case a simple name cannot be used to refer to 
the declared entity.
<p><a name="62323"></a>
The example:<p>
<pre><a name="34052"></a>
class Test {
<a name="34053"></a>	static int x = 1;
<a name="34054"></a>	public static void main(String[] args) {
<a name="34055"></a>		int x = 0;
<a name="34056"></a>		System.out.print("x=" + x);
<a name="34057"></a>		System.out.println(", Test.x=" + Test.x);
<a name="34058"></a>	}
<a name="34059"></a>}
</pre><a name="34060"></a>
produces the output:
<p><pre><a name="34061"></a>x=0, Test.x=1
</pre><a name="34062"></a>
This example declares:
<p><ul><a name="62327"></a>
<li>a class <code>Test</code>
<a name="62331"></a>
<li>a class (<code>static</code>) variable <code>x</code> that is a member of the class <code>Test</code>
<a name="62332"></a>
<li>a class method <code>main</code> that is a member of the class <code>Test</code>
<a name="62333"></a>
<li>a parameter <code>args</code> of the <code>main</code> method
<a name="62334"></a>
<li>a local variable <code>x</code> of the <code>main</code> method
</ul><a name="34066"></a>
Since the scope of a class variable includes the entire body of the class <a href="8.doc.html#21831">(&#167;8.2)</a> the class variable <code>x</code> would normally be available throughout the entire body of the method <code>main</code>. In this example, however, the class variable <code>x</code> is hidden within the body of the method <code>main</code> by the declaration of the local variable <code>x</code>.<p>
<a name="62312"></a>
A local variable has as its scope the rest of the block in which it is declared <a href="14.doc.html#32644">(&#167;14.3.2)</a>; in this case this is the rest of the body of the <code>main</code> method, namely its initializer "<code>0</code>" and the invocations of <code>print</code> and <code>println</code>.<p>
<a name="62314"></a>
This means that:<p>
<ul><a name="62313"></a>
<li>The expression "<code>x</code>" in the invocation of <code>print</code> refers to (denotes) the value of the local variable <code>x</code>.
<a name="62320"></a>
<li>The invocation of <code>println</code> uses a qualified name <a href="6.doc.html#33916">(&#167;6.6)</a> <code>Test.x</code>, which uses the class type name <code>Test</code> to access the class variable <code>x</code>, because the declaration of <code>Test.x</code> is hidden at this point and cannot be referred to by its simple name.
</ul><a name="62307"></a>
If the standard naming conventions <a href="6.doc.html#11186">(&#167;6.8)</a> are followed, then hiding that would make the identification of separate naming contexts matter should be rare. The following contrived example involves hiding because it does not follow the standard naming conventions:<p>
<pre><a name="34080"></a>
class Point { int x, y; }
<a name="34083"></a>
class Test {
<a name="34084"></a>
	static Point Point(int x, int y) {
<a name="34085"></a>		Point p = new Point();
<a name="34086"></a>		p.x = x; p.y = y;
<a name="34087"></a>		return p;
<a name="34088"></a>	}
<br><a name="34089"></a>
	public static void main(String[] args) {
<a name="34090"></a>		int Point;
<a name="34091"></a>		Point[] pa = new Point[2];
<a name="34092"></a>		for (Point = 0; Point &lt; 2; Point++) {
<a name="34093"></a>			pa[Point] = new Point();
<a name="34094"></a>			pa[Point].x = Point;
<a name="34095"></a>			pa[Point].y = Point;
<a name="34096"></a>		}
<a name="34097"></a>		System.out.println(pa[0].x + "," + pa[0].y);
<a name="34098"></a>		System.out.println(pa[1].x + "," + pa[1].y);
<a name="34099"></a>		Point p = Point(3, 4);
<a name="34100"></a>		System.out.println(p.x + "," + p.y);
<a name="34101"></a>	}
<br><a name="34102"></a>}
</pre><a name="34103"></a>
This compiles without error and executes to produce the output:
<p><pre><a name="34104"></a>
0,0
<a name="34105"></a>1,1<br>
3,4
</pre><a name="34106"></a>
Within the body of <code>main</code>, the lookups of <code>Point</code> find different declarations depending
on the context of the use:
<p><ul><a name="34107"></a>
<li>In the expression "<code>new</code> <code>Point[2]</code>", the two occurrences of the class instance creation expression "<code>new</code> <code>Point()</code>", and at the start of three different local variable declaration statements, the <code>Point</code> is a <i>TypeName</i> <a href="6.doc.html#21721">(&#167;6.5.4)</a> and denotes the class type <code>Point</code> in each case.
<a name="34268"></a>
<li>In the method invocation expression "<code>Point(3,</code> <code>4)</code>" the occurrence of <code>Point</code> is a <i>MethodName </i><a href="6.doc.html#21652">(&#167;6.5.6)</a> and denotes the class (<code>static</code>) method <code>Point</code>.
<a name="34114"></a>
<li>All other names are <i>ExpressionName</i>s <a href="6.doc.html#21650">(&#167;6.5.5)</a> and refer to the local variable <code>Point</code>.
</ul><a name="34119"></a>
The example:
<p><pre><a name="34120"></a>import java.util.*;
</pre><pre><a name="34121"></a>
class Vector {
<a name="34122"></a>	int val[] = { 1 , 2 };
<a name="34123"></a>}
<br><a name="34124"></a>
class Test {
<a name="34125"></a>	public static void main(String[] args) {
<a name="34126"></a>		Vector v = new Vector();
<a name="34127"></a>		System.out.println(v.val[0]);
<a name="34128"></a>	}
<a name="34129"></a>}
</pre><a name="34130"></a>
compiles and prints:
<p><pre><a name="34131"></a>1
</pre><a name="56469"></a>
using the class <code>Vector</code> declared here in preference to class <code>java.util.Vector</code> 
that might be imported on demand.
<p><a name="31814"></a>
<h2>6.4    Members and Inheritance</h2>
<a name="23209"></a>
Packages and reference types have <i>members</i>. The members of a package <a href="7.doc.html#34412">(&#167;7)</a> are 
subpackages <a href="7.doc.html#26535">(&#167;7.1)</a> and all the class <a href="8.doc.html#3857">(&#167;8)</a> and interface <a href="9.doc.html#238678">(&#167;9)</a> types declared in all 
the compilation units <a href="7.doc.html#40031">(&#167;7.3)</a> of the package. The members of a reference type 
<a href="4.doc.html#9317">(&#167;4.3)</a> are fields (<a href="8.doc.html#40898">&#167;8.3</a>, <a href="9.doc.html#78642">&#167;9.3</a>, <a href="10.doc.html#11364">&#167;10.7</a>) and methods (<a href="8.doc.html#40420">&#167;8.4</a>, <a href="9.doc.html#78651">&#167;9.4</a>). Members are either 
declared in the type, or <i>inherited </i>because they are accessible members of a superclass
or superinterface which are neither hidden nor overridden <a href="8.doc.html#228745">(&#167;8.4.6)</a>.
<p><a name="56531"></a>
This section provides an overview of the members of packages and reference types here, as background for the discussion of qualified names and the determination of the meaning of names. For a complete description of membership, see <a href="7.doc.html#26535">&#167;7.1</a>, <a href="8.doc.html#21831">&#167;8.2</a>, <a href="9.doc.html#32392">&#167;9.2</a>, and <a href="10.doc.html#11364">&#167;10.7</a>.<p>
<a name="34993"></a>
<h3>6.4.1    The Members of a Package</h3>
<a name="23133"></a>
A member of a package <a href="7.doc.html#34412">(&#167;7)</a> is a subpackage <a href="7.doc.html#26535">(&#167;7.1)</a>, or a class <a href="8.doc.html#3857">(&#167;8)</a> or interface 
<a href="9.doc.html#238678">(&#167;9)</a> type declared in a compilation unit <a href="7.doc.html#40031">(&#167;7.3)</a> of the package.
<p><a name="56555"></a>
In general, the subpackages of a package are determined by the host system <a href="7.doc.html#37758">(&#167;7.2)</a>. However, the standard package <code>java</code> always includes the subpackages <code>lang</code>, <code>util</code>, <code>io</code>, and <code>net</code> and may include other subpackages. No two distinct members of the same package may have the same simple name <a href="7.doc.html#26535">(&#167;7.1)</a>, but members of different packages may have the same simple name. For example, it is possible to declare a package:<p>
<pre><a name="34982"></a>package vector;
<a name="34983"></a>public class Vector { Object[] vec; }
</pre><a name="34986"></a>
that has as a member a <code>public</code> class named <code>Vector</code>, even though the standard 
package <code>java.util</code> also declares a class named <code>Vector</code>. These two class types 
are different, reflected by the fact that they have different fully qualified names 
<a href="6.doc.html#25430">(&#167;6.7)</a>. The fully qualified name of this example <code>Vector</code> is <code>vector.Vector</code>, 
whereas <code>java.util.Vector</code> is the fully qualified name of the standard <code>Vector</code> 
class. Because the package <code>vector</code> contains a class named <code>Vector</code>, it cannot also 
have a subpackage named <code>Vector</code>.
<p><a name="34757"></a>
<h3>6.4.2    The Members of a Class Type</h3>
<a name="34765"></a>
The members of a class type <a href="8.doc.html#21831">(&#167;8.2)</a> are fields and methods. The members of a 
class type are all of the following:
<p><ul><a name="34768"></a>
<li>Members inherited from its direct superclass <a href="8.doc.html#21723">(&#167;8.1.3)</a>, if it has one (the class <code>Object</code> has no direct superclass)
<a name="34777"></a>
<li>Members inherited from any direct superinterfaces <a href="8.doc.html#34031">(&#167;8.1.4)</a>
<a name="34778"></a>
<li>Members declared in the body of the class <a href="8.doc.html#18988">(&#167;8.1.5)</a>
</ul><a name="62337"></a>
Constructors <a href="8.doc.html#41652">(&#167;8.6)</a> are not members.
<p><a name="31685"></a>
There is no restriction against a field and a method of a class type having the same simple name.<p>
<a name="56650"></a>
A class may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error (<a href="6.doc.html#54547">&#167;6.5.6.2</a>, <a href="8.doc.html#21831">&#167;8.2</a>).<p>
<a name="31689"></a>
In the example:<p>
<pre><a name="25284"></a>
interface Colors {
<a name="25285"></a>	int WHITE = 0, BLACK = 1;
<a name="25286"></a>}
<a name="31681"></a>
interface Separates {
<a name="25287"></a>	int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
<a name="25288"></a>}
<a name="25289"></a>
class Test implements Colors, Separates {
<a name="25290"></a>	public static void main(String[] args) {
<a name="25291"></a>		System.out.println(BLACK); // compile-time error: ambiguous
<a name="25292"></a>	}
<a name="25293"></a>}
</pre><a name="25294"></a>
the name <code>BLACK</code> in the method <code>main</code> is ambiguous, because class <code>Test</code> has two 
members named <code>BLACK</code>, one inherited from <code>Colors</code> and one from <code>Separates</code>.
<p><a name="23306"></a>
A class type may have two or more methods with the same simple name if the methods have different signatures <a href="8.doc.html#38649">(&#167;8.4.2)</a>, that is, if they have different numbers of parameters or different parameter types in at least one parameter position. Such a method member name is said to be <i>overloaded</i>.<p>
<a name="31700"></a>
A class type may contain a declaration for a method with the same name and the same signature as a method that would otherwise be inherited from a superclass or superinterface. In this case, the method of the superclass or superinterface is not inherited. If the method not inherited is <code>abstract</code>, then the new declaration is said to <i>implement</i> it; if the method not inherited is not <code>abstract</code>, then the new declaration is said to <i>override</i> it.<p>
<a name="31699"></a>
In the example:<p>
<pre><a name="38566"></a>
class Point {
<a name="38567"></a>	float x, y;
<a name="38568"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<a name="31704"></a>	void move(float dx, float dy) { x += dx; y += dy; }
<a name="31705"></a>	public String toString() { return "("+x+","+y+")"; }
<a name="31706"></a>}
</pre><a name="31707"></a>
the class <code>Point</code> has two members that are methods with the same name, <code>move</code>. 
The overloaded <code>move</code> method of class <code>Point</code> chosen for any particular method 
invocation is determined at compile time by the overloading resolution procedure 
given in <a href="15.doc.html#20448">&#167;15.11</a>.
<p><a name="62345"></a>
In this example, the members of the class <code>Point</code> are the <code>float</code> instance variables <code>x</code> and <code>y</code> declared in <code>Point</code>, the two declared <code>move</code> methods, the declared <code>toString</code> method, and the members that <code>Point</code> inherits from its implicit direct superclass <code>Object</code> <a href="4.doc.html#11055">(&#167;4.3.2)</a>, such as the method <code>hashCode</code> <a href="javalang.doc1.html#13784">(&#167;20.1.4)</a>. Note that <code>Point</code> does not inherit the <code>toString</code> method <a href="javalang.doc1.html#1152">(&#167;20.1.2)</a> of class <code>Object</code> because that method is overridden by the declaration of the <code>toString</code> method in class <code>Point</code>.<p>
<a name="34849"></a>
<h3>6.4.3    The Members of an Interface Type</h3>
<a name="31765"></a>
The members of an interface type <a href="9.doc.html#32392">(&#167;9.2)</a> are fields and methods. The members of 
an interface are all of the following:
<p><ul><a name="31784"></a>
<li>Members inherited from any direct superinterfaces <a href="9.doc.html#78598">(&#167;9.1.3)</a>
<a name="31788"></a>
<li>Members declared in the body of the interface <a href="9.doc.html#236431">(&#167;9.1.4)</a>
</ul><a name="31831"></a>
An interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any such field by its simple name results in a compile-time error (<a href="6.doc.html#22022">&#167;6.5.5.1</a>, <a href="9.doc.html#32392">&#167;9.2</a>).<p>
<a name="61795"></a>
In the example:<p>
<pre><a name="20498"></a>
interface Colors {
<a name="20499"></a>	int WHITE = 0, BLACK = 1;
<a name="20500"></a>}
<a name="31851"></a>
interface Separates {
<a name="20501"></a>	int CYAN = 0, MAGENTA = 1, YELLOW = 2, BLACK = 3;
<a name="20502"></a>}
<a name="35253"></a>interface ColorsAndSeparates extends Colors, Separates {<br>
	int DEFAULT = BLACK;								 	// compile-time error: ambiguous<br>
}
</pre><a name="35254"></a>
the members of the interface <code>ColorsAndSeparates</code> include those members 
inherited from <code>Colors</code> and those inherited from <code>Separates</code>, namely <code>WHITE</code>, 
<code>BLACK</code> (first of two), <code>CYAN</code>, <code>MAGENTA</code>, <code>YELLOW</code>, and <code>BLACK</code> (second of two). The 
member name <code>BLACK</code> is ambiguous in the interface <code>ColorsAndSeparates</code>.
<p><a name="27725"></a>
<h3>6.4.4    The Members of an Array Type</h3>
<a name="36005"></a>
The members of an array type <a href="10.doc.html#11364">(&#167;10.7)</a> are all of the following:
<p><ul><a name="23342"></a>
<li>Members inherited from its implicit superclass <code>Object</code> (<a href="4.doc.html#11055">&#167;4.3.2</a>, <a href="javalang.doc1.html#46442">&#167;20.1</a>)
<a name="23344"></a>
<li>The field <code>length</code>, which is a constant (<code>final</code>) field of every array; its type is <code>int</code> and it contains the number of components of the array
</ul><a name="27727"></a>
The example:
<p><pre><a name="27728"></a>
class Test {
<a name="27729"></a>	public static void main(String[] args) {
<a name="27730"></a>		int[] ia = new int[3];
<a name="27731"></a>		int[] ib = new int[6];
<a name="27733"></a>		System.out.println(ia.getClass() == ib.getClass());
<a name="31873"></a>		System.out.println("ia has length=" + ia.length);
<a name="27734"></a>	}
<a name="27735"></a>}
</pre><a name="27736"></a>
produces the output:
<p><pre><a name="31879"></a>
true
<a name="27737"></a>ia has length=3
</pre><a name="27739"></a>
This example uses the method <code>getClass</code> inherited from class <code>Object</code> and the 
field <code>length</code>. The result of the comparison of the <code>Class</code> objects in the second 
<code>println</code> demonstrates that all arrays whose components are of type <code>int</code> are 
instances of the same array type, which is <code>int[]</code>.
<p><a name="20569"></a>
<h2>6.5    Determining the Meaning of a Name</h2>
<a name="22344"></a>
The meaning of a name in Java depends on the context in which it is used. The 
determination of the meaning of a name requires three steps. First, context causes 
a name syntactically to fall into one of five categories: <i>PackageName</i>, <i>TypeName</i>, 
<i>ExpressionName</i>, <i>MethodName</i>, or <i>AmbiguousName</i>. Second, a name that is initially
classified by its context as an <i>AmbiguousName</i> is then reclassified by certain 
scoping rules to be a <i>PackageName</i>, <i>TypeName</i>, or <i>ExpressionName</i>. Third, the 
resulting category then dictates the final determination of the meaning of the name 
(or a compilation error if the name has no meaning).
<p><ul><pre>
<i>PackageName:<br>
</i>	<i>Identifier<br>
</i>	<i>PackageName</i><code> . </code><i>Identifier
</i>
<i>TypeName:<br>
</i>	<i>Identifier<br>
</i>	<i>PackageName</i><code> . </code><i>Identifier
</i>
<i>ExpressionName:<br>
</i>	<i>Identifier<br>
</i>	<i>AmbiguousName</i><code> . </code><i>Identifier
</i>
<i>MethodName:<br>
</i>	<i>Identifier<br>
</i>	<i>AmbiguousName</i><code> . </code><i>Identifier
</i>
<i>AmbiguousName:<br>
</i>	<i>Identifier<br>
</i>	<i>AmbiguousName</i><code> . </code><i>Identifier
</i></pre></ul><a name="32744"></a>
Java's use of context helps to minimize name conflicts between entities of different kinds. Such conflicts will be rare if the naming conventions described in <a href="6.doc.html#11186">&#167;6.8</a> are followed. Nevertheless, conflicts may arise unintentionally as types developed by different programmers or different organizations evolve. For example, types, methods, and fields may have the same name. Java never has trouble distinguishing between a method and a field with the same name, since the context of a use always tells whether a method or a field is intended.<p>
<a name="32740"></a>
<h3>6.5.1    Syntactic Classification of a Name According to Context</h3>
<a name="32741"></a>
A name is syntactically classified as a <i>PackageName</i> in these contexts:
<p><ul><a name="32159"></a>
<li>In a package declaration <a href="7.doc.html#26619">(&#167;7.4)</a>
<a name="32164"></a>
<li>In a type-import-on-demand declaration <a href="7.doc.html#26725">(&#167;7.5.2)</a>
<a name="32492"></a>
<li>To the left of the "<code>.</code>" in a qualified <i>PackageName</i>
<a name="32494"></a>
<li>To the left of the "<code>.</code>" in a qualified <i>TypeName</i>
</ul><a name="32149"></a>
A name is syntactically classified as a <i>TypeName</i> in these contexts:
<p><ul><a name="32174"></a>
<li>In a single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a>
<a name="32178"></a>
<li>In an <code>extends</code> clause in a class declaration <a href="8.doc.html#21723">(&#167;8.1.3)</a>
<a name="32182"></a>
<li>In an <code>implements</code> clause in a class declaration <a href="8.doc.html#34031">(&#167;8.1.4)</a>
<a name="34302"></a>
<li>In an <code>extends</code> clause in an interface declaration <a href="9.doc.html#78598">(&#167;9.1.3)</a>
<a name="32290"></a>
<li>As a <i>Type</i> (or the part of a <i>Type</i> that remains after all brackets are deleted) in any of the following contexts:
<ul>
<a name="32310"></a>
<li>In a field declaration (<a href="8.doc.html#40898">&#167;8.3</a>, <a href="9.doc.html#78642">&#167;9.3</a>)
<a name="32322"></a>
<li>As the result type of a method (<a href="8.doc.html#40420">&#167;8.4</a>, <a href="9.doc.html#78651">&#167;9.4</a>)
<a name="32355"></a>
<li>As the type of a formal parameter of a method or constructor (<a href="8.doc.html#38698">&#167;8.4.1</a>, <a href="8.doc.html#29488">&#167;8.6.1</a>, <a href="9.doc.html#78651">&#167;9.4</a>)
<a name="32266"></a>
<li>As the type of an exception that can be thrown by a method or constructor (<a href="8.doc.html#78323">&#167;8.4.4</a>, <a href="8.doc.html#244611">&#167;8.6.4</a>, <a href="9.doc.html#78651">&#167;9.4</a>)
<a name="32224"></a>
<li>As the type of a local variable <a href="14.doc.html#5920">(&#167;14.3)</a>
<a name="32225"></a>
<li>As the type of an exception parameter in a <code>catch</code> clause of a <code>try</code> statement <a href="14.doc.html#79311">(&#167;14.18)</a>
<a name="32233"></a>
<li>As the class type of an instance that is to be created in a class instance creation expression <a href="15.doc.html#41147">(&#167;15.8)</a>
<a name="32240"></a>
<li>As the element type of an array to be created in an array creation expression <a href="15.doc.html#46168">(&#167;15.9)</a>
<a name="32244"></a>
<li>As the type mentioned in the cast operator of a cast expression <a href="15.doc.html#238146">(&#167;15.15)</a>
<a name="32248"></a>
<li>As the type that follows the <code>instanceof</code> relational operator <a href="15.doc.html#80289">(&#167;15.19.2)</a>
</ul>
</ul><a name="32435"></a>
A name is syntactically classified as an <i>ExpressionName</i> in these contexts:
<p><ul><a name="32464"></a>
<li>As the array reference expression in an array access expression <a href="15.doc.html#239587">(&#167;15.12)</a>
<a name="32459"></a>
<li>As a <i>PostfixExpression</i> <a href="15.doc.html#36254">(&#167;15.13)</a>
<a name="32477"></a>
<li>As the left-hand operand of an assignment operator <a href="15.doc.html#5281">(&#167;15.25)</a>
</ul><a name="32437"></a>
A name is syntactically classified as a <i>MethodName</i> in this context:
<p><ul><a name="32480"></a>
<li>Before the "<code>(</code>" in a method invocation expression <a href="15.doc.html#20448">(&#167;15.11)</a>
</ul><a name="32439"></a>
A name is syntactically classified as an <i>AmbiguousName</i> in these contexts:
<p><ul><a name="32496"></a>
<li>To the left of the "<code>.</code>" in a qualified <i>ExpressionName</i>
<a name="32499"></a>
<li>To the left of the "<code>.</code>" in a qualified <i>MethodName</i>
<a name="32501"></a>
<li>To the left of the "<code>.</code>" in a qualified <i>AmbiguousName</i>
</ul><a name="32725"></a>
<h3>6.5.2    Reclassification of Contextually Ambiguous Names</h3>
<a name="32133"></a>
An <i>AmbiguousName</i> is then reclassified as follows:
<p><ul><a name="32505"></a>
<li>If the <i>AmbiguousName</i> is a simple name, consisting of a single <i>Identifier</i>:
<ul>
<a name="32544"></a>
<li>If the <i>Identifier</i> appears within the scope <a href="6.doc.html#33623">(&#167;6.3)</a> of a local variable declaration <a href="14.doc.html#5920">(&#167;14.3)</a> or parameter declaration (<a href="8.doc.html#38698">&#167;8.4.1</a>, <a href="8.doc.html#29488">&#167;8.6.1</a>, <a href="14.doc.html#79311">&#167;14.18</a>) with that name, then the <i>AmbiguousName</i> is reclassified as an <i>ExpressionName</i>.
<a name="32569"></a>
<li>Otherwise, consider the class or interface <i>C</i> within whose declaration the <i>Identifier</i> occurs. If <i>C</i> has one or more fields with that name, which may be either declared within it or inherited, then the <i>AmbiguousName</i> is reclassified as an <i>ExpressionName</i>.
<a name="32843"></a>
<li>Otherwise, if a type of that name is declared in the compilation unit <a href="7.doc.html#40031">(&#167;7.3)</a> containing the <i>Identifier</i>, either by a single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> or by a class or interface type declaration <a href="7.doc.html#26783">(&#167;7.6)</a>, then the <i>AmbiguousName</i> is reclassified as a <i>TypeName</i>.
<a name="32853"></a>
<li>Otherwise, if a type of that name is declared in another compilation unit <a href="7.doc.html#40031">(&#167;7.3)</a> of the package <a href="7.doc.html#26535">(&#167;7.1)</a> of the compilation unit containing the <i>Identifier</i>, &#32;then the <i>AmbiguousName</i> is reclassified as a <i>TypeName</i>.
<a name="32860"></a>
<li>Otherwise, if a type of that name is declared by exactly one type-import-on-demand declaration <a href="7.doc.html#26725">(&#167;7.5.2)</a> of the compilation unit containing the <i>Identifier</i>, &#32;then the <i>AmbiguousName</i> is reclassified as a <i>TypeName</i>.
<a name="32864"></a>
<li>Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit containing the <i>Identifier</i>, then a compile-time error results.
<a name="32535"></a>
<li>Otherwise, the <i>AmbiguousName</i> is reclassified as a <i>PackageName</i>. A later step determines whether or not a package of that name actually exists.
</ul>
<a name="32506"></a>
<li>If the <i>AmbiguousName</i> is a qualified name, consisting of a name, a "<code>.</code>", and an <i>Identifier</i>, then the name to the left of the "<code>.</code>" is first reclassified, for it is itself an <i>AmbiguousName</i>. There is then a choice:
<ul>
<a name="32509"></a>
<li>If the name to the left of the "<code>.</code>" is reclassified as a <i>PackageName</i>, then there is a further choice:
<ul>
<a name="32700"></a>
<li>If there is a package whose name is the name to the left of the "<code>.</code>" and that package contains a declaration of a type whose name is the same as the <i>Identifier</i>, then this <i>AmbiguousName</i> is reclassified as a <i>TypeName</i>.
<a name="32713"></a>
<li>Otherwise, this <i>AmbiguousName</i> is reclassified as a <i>PackageName</i>. A later step determines whether or not a package of that name actually exists.
</ul>
<a name="32511"></a>
<li>If the name to the left of the "<code>.</code>" is reclassified as a <i>TypeName</i>, then this <i>AmbiguousName</i> is reclassified as an <i>ExpressionName</i>.
<a name="32513"></a>
<li>If the name to the left of the "<code>.</code>" is reclassified as an <i>ExpressionName</i>, then this <i>AmbiguousName</i> is reclassified as an <i>ExpressionName</i>.
</ul>
</ul><a name="60456"></a>
As an example, consider the following contrived "library code":<p>
<pre><br><a name="60457"></a>package ORG.rpgpoet;
<br><br><a name="60459"></a>import java.util.Random;
<br><a name="60458"></a>interface Music { Random[] wizards = new Random[4]; }
</pre><a name="60464"></a>
and then consider this example code in another package:
<p><pre><br><a name="60521"></a>package bazola;
<br></pre><pre><a name="60467"></a>
class Gabriel {
<a name="60466"></a>	static int n = ORG.rpgpoet.Music.wizards.length;
<a name="60465"></a>}
</pre><a name="60483"></a>
First of all, the name <code>ORG.rpgpoet.Music.wizards.length</code> is classified as an 
<i>ExpressionName</i> because it functions as a <i>PostfixExpression</i>. Therefore, each of 
the names:
<p><pre><a name="60488"></a>
ORG.rpgpoet.Music.wizards
<a name="60490"></a>ORG.rpgpoet.Music
<a name="60492"></a>ORG.rpgpoet
<a name="60494"></a>ORG
</pre><a name="60515"></a>
is initially classified as an <i>AmbiguousName</i>. These are then reclassified:
<p><ul><a name="60526"></a>
<li>Assuming that there is no class or interface named <code>ORG</code> in any other compilation unit of package <code>bazola</code>, then the simple name <code>ORG</code> is reclassified as a <i>PackageName</i>.
<a name="60530"></a>
<li>Next, assuming that there is no class or interface named <code>rpgpoet</code> in any compilation unit of package <code>ORG</code> (and we know that there is no such class or interface because package <code>ORG</code> has a subpackage named <code>rpgpoet</code>), the qualified name <code>ORG.rpgpoet</code> is reclassified as a <i>PackageName</i>.
<a name="60542"></a>
<li>Next, because package <code>ORG.rpgpoet</code> has an interface type named <code>Music</code>, the qualified name <code>ORG.rpgpoet.Music</code> is reclassified as a <i>TypeName</i>.
<a name="60540"></a>
<li>Finally, because the name <code>ORG.rpgpoet.Music</code> is a <i>TypeName</i>, the qualified name <code>ORG.rpgpoet.Music.wizards</code> is reclassified as an <i>ExpressionName</i>.
</ul><a name="22349"></a>
<h3>6.5.3    Meaning of Package Names</h3>
<a name="32757"></a>
The meaning of a name classified as a <i>PackageName</i> is determined as follows.
<p><a name="22481"></a>
<h4>6.5.3.1    Simple Package Names</h4>
<a name="21719"></a>
If a package name consists of a single <i>Identifier</i>, then this identifier denotes a top-
level package named by that identifier. If no package of that name is accessible, as 
determined by the host system <a href="7.doc.html#13180">(&#167;7.4.3)</a>, then a compile-time error occurs.
<p><a name="22482"></a>
<h4>6.5.3.2    Qualified Package Names</h4>
<a name="21727"></a>
If a package name is of the form <i>Q</i><code>.</code><i>Id</i>, then <i>Q</i> must also be a package name. The 
package name <i>Q</i><code>.</code><i>Id</i> names a package that is the member named <i>Id</i> within the 
package named by <i>Q</i>. If <i>Q</i> does not name an accessible package or <i>Id</i> does not 
name an accessible subpackage of that package, then a compile-time error occurs.
<p><a name="21721"></a>
<h3>6.5.4    Meaning of Type Names</h3>
<a name="32763"></a>
The meaning of a name classified as a <i>TypeName</i> is determined as follows.
<p><a name="21810"></a>
<h4>6.5.4.1    Simple Type Names</h4>
<a name="32799"></a>
If a type name consists of a single <i>Identifier</i>, then the identifier must occur in the 
scope of a declaration of a type with this name, or a compile-time error occurs. It 
is possible that the identifier occurs within the scope of more than one type with 
that name, in which case the type denoted by the name is determined as follows:
<p><ul><a name="21741"></a>
<li>If a type with that name is declared in the current compilation unit <a href="7.doc.html#40031">(&#167;7.3)</a>, either by a single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> or by a declaration of a class or interface &#32;type <a href="7.doc.html#26783">(&#167;7.6)</a>, then the simple type name denotes that type.
<a name="21751"></a>
<li>Otherwise, if a type with that name is declared in another compilation unit <a href="7.doc.html#40031">(&#167;7.3)</a> of the package <a href="7.doc.html#26535">(&#167;7.1)</a> containing the identifier, then the identifier denotes that type. Note that, in systems that store compilation units in a file system, such a compilation unit must have a file name that is the name of the type <a href="7.doc.html#26783">(&#167;7.6)</a>.
<a name="21758"></a>
<li>Otherwise, if a type of that name is declared by exactly one type-import-on-demand declaration <a href="7.doc.html#26725">(&#167;7.5.2)</a> of the compilation unit containing the identifier, then the simple type name denotes that type.
<a name="32932"></a>
<li>Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit, then the name is ambiguous as a type name; a compile-time error occurs.
<a name="32933"></a>
<li>Otherwise, the name is undefined as a type name; a compile-time error occurs.
</ul><a name="32934"></a>
This order for considering type declarations is designed to choose the most 
explicit of two or more applicable type declarations.
<p><a name="21811"></a>
<h4>6.5.4.2    Qualified Type Names</h4>
<a name="32818"></a>
If a type name is of the form <i>Q</i><code>.</code><i>Id</i>, then <i>Q</i> must be a package name. The type 
name <i>Q</i><code>.</code><i>Id</i> names a type that is the member named <i>Id</i> within the package named 
by <i>Q</i>. If <i>Q</i> does not name an accessible package, or <i>Id</i> does not name a type within 
that package, or the type named <i>Id</i> within that package is not accessible <a href="6.doc.html#33916">(&#167;6.6)</a>, 
then a compile-time error occurs.
<p><a name="32816"></a>
The example:<p>
<pre><a name="21789"></a>package wnj.test;
</pre><pre><a name="21790"></a>
class Test {
<a name="21791"></a>	public static void main(String[] args) {
<a name="21792"></a>		java.util.Date date =
<a name="21793"></a>			new java.util.Date(System.currentTimeMillis());
<a name="21794"></a>		System.out.println(date.toLocaleString());
<a name="21795"></a>	}
<a name="21796"></a>}
</pre><a name="21797"></a>
produced the following output the first time it was run:
<p><pre><a name="21798"></a>Sun Jan 21 22:56:29 1996
</pre><a name="21799"></a>
In this example:
<p><ul><a name="21800"></a>
<li>The name <code>wnj.test</code> must name a package on the host system. It is resolved by first looking for the package <code>wnj</code>, using the procedure described in <a href="6.doc.html#22481">&#167;6.5.3.1</a>, and then making sure that the subpackage <code>test</code> of this package is accessible.
<a name="21807"></a>
<li>The name <code>java.util.Date</code> <a href="javautil.doc3.html#7433">(&#167;21.3)</a> must denote a type, so we first use the procedure recursively to determine if <code>java.util</code> is an accessible package, which it is, and then look to see if the type <code>Date</code> is accessible in this package.
</ul><a name="21650"></a>
<h3>6.5.5    Meaning of Expression Names</h3>
<a name="32767"></a>
The meaning of a name classified as an <i>ExpressionName</i> is determined as follows.
<p><a name="22022"></a>
<h4>6.5.5.1    Simple Expression Names</h4>
<a name="22023"></a>
If an expression name consists of a single <i>Identifier</i>, then:
<p><ul><a name="22030"></a>
<li>If the <i>Identifier</i> appears within the scope <a href="6.doc.html#33623">(&#167;6.3)</a> of a local variable declaration <a href="14.doc.html#5920">(&#167;14.3)</a> or parameter declaration (<a href="8.doc.html#38698">&#167;8.4.1</a>, <a href="8.doc.html#29488">&#167;8.6.1</a>, <a href="14.doc.html#79311">&#167;14.18</a>) with that name, then the expression name denotes a variable, that is, that local variable or parameter. Local variables and parameters are never hidden (<a href="6.doc.html#33623">&#167;6.3</a>, <a href="6.doc.html#34133">&#167;6.3.1</a>, <a href="14.doc.html#5920">&#167;14.3</a>), so there is necessarily at most one such local variable or parameter. The type of the expression name is the declared type of the local variable or parameter.
<a name="22052"></a>
<li>Otherwise, if the <i>Identifier</i> appears within a class declaration <a href="8.doc.html#3857">(&#167;8)</a>:
<ul>
<a name="22062"></a>
<li>If there is not exactly one member of that class <a href="8.doc.html#21831">(&#167;8.2)</a> that is a field with that name, then a compile-time error results.
<a name="22063"></a>
<li>Otherwise, if the single member field with that name is declared <code>final</code> <a href="8.doc.html#35962">(&#167;8.3.1.2)</a>, then the expression name denotes the value of the field. The type of the expression name is the declared type of the field. If the <i>Identifier</i> appears in a context that requires a variable and not a value, then a compile-time error occurs.
<a name="22077"></a>
<li>Otherwise, the expression name denotes a variable, the single member field with that name. The type of the expression name is the field's declared type.
</ul>
</ul><ul><a name="60351"></a>
<br><br>If the field is an instance variable <a href="8.doc.html#37544">(&#167;8.3.1.1)</a>, the expression name must appear within the declaration of an instance method <a href="8.doc.html#40420">(&#167;8.4)</a>, constructor <a href="8.doc.html#41652">(&#167;8.6)</a>, or instance variable initializer <a href="8.doc.html#38013">(&#167;8.3.2.2)</a>. If it appears within a <code>static</code> method <a href="8.doc.html#229128">(&#167;8.4.3.2)</a>, static initializer <a href="8.doc.html#39245">(&#167;8.5)</a>, or initializer for a <code>static</code> variable (<a href="8.doc.html#37544">&#167;8.3.1.1</a>, <a href="12.doc.html#44630">&#167;12.4.2</a>), then a compile-time error occurs.
</ul><ul><a name="60376"></a>
<li>Otherwise, the identifier appears within an interface declaration <a href="9.doc.html#238678">(&#167;9)</a>:
<ul>
<a name="60380"></a>
<li>If there is not exactly one member of that interface <a href="9.doc.html#32392">(&#167;9.2)</a> that is a field with that name, then a compile-time error results.
<a name="32963"></a>
<li>Otherwise, the expression name denotes the value of the single member field of that name. The type of the expression name is the declared type of the field. If the <i>Identifier</i> appears in a context that requires a variable and not a value, then a compile-time error occurs.
</ul>
</ul><a name="22118"></a>
In the example:
<p><pre><a name="22119"></a>
class Test {
<br><a name="22120"></a>	static int v;
<br><br><a name="61612"></a>	static final int f = 3;
<br><a name="61613"></a>
	public static void main(String[] args) {
<a name="61614"></a>		int i;
<a name="22124"></a>		i = 1;
<a name="22125"></a>		v = 2;
<a name="22126"></a>		f = 33;										// compile-time error
<a name="22127"></a>		System.out.println(i + " " + v + " " + f);
<a name="22128"></a>	}
<br><a name="22129"></a>}
</pre><a name="22130"></a>
the names used as the left-hand-sides in the assignments to <code>i</code>, <code>v</code>, and <code>f</code> denote the 
local variable <code>i</code>, the field <code>v</code>, and the value of <code>f</code> (not the variable <code>f</code>, because <code>f</code> is a 
<code>final</code> variable). The example therefore produces an error at compile time 
because the last assignment does not have a variable as its left-hand side. If the 
erroneous assignment is removed, the modified code can be compiled and it will 
produce the output:
<p><pre><a name="22131"></a>1 2 3
</pre><a name="22133"></a>
<h4>6.5.5.2    Qualified Expression Names</h4>
<a name="33085"></a>
If an expression name is of the form <i>Q</i><code>.</code><i>Id</i>, then <i>Q</i> has already been classified as a 
package name, a type name, or an expression name:
<p><ul><a name="22747"></a>
<li>If <i>Q</i> is a package name, then a compile-time error occurs.
<a name="22294"></a>
<li>If <i>Q</i> is a type name that names a class type <a href="8.doc.html#3857">(&#167;8)</a>, then:
<ul>
<a name="22298"></a>
<li>If there is not exactly one accessible <a href="6.doc.html#33916">(&#167;6.6)</a> member of the class type that is a field named <i>Id</i>, then a compile-time error occurs.
<a name="22299"></a>
<li>Otherwise, if the single accessible member field is not a class variable (that is, it is not declared <code>static</code>), then a compile-time error occurs.
<a name="41289"></a>
<li>Otherwise, if the class variable is declared <code>final</code>, then <i>Q</i><code>.</code><i>Id</i> denotes the value of the class variable. The type of the expression <i>Q</i><code>.</code><i>Id</i> is the declared type of the class variable. If <i>Q</i><code>.</code><i>Id</i> appears in a context that requires a variable and not a value, then a compile-time error occurs.
<a name="22303"></a>
<li>Otherwise, <i>Q</i><code>.</code><i>Id</i> denotes the class variable. The type of the expression <i>Q</i><code>.</code><i>Id</i> is the declared type of the class variable.
</ul>
<a name="22145"></a>
<li>If <i>Q</i> is a type name that names an interface type <a href="9.doc.html#238678">(&#167;9)</a>, then:
<ul>
<a name="33167"></a>
<li>If there is not exactly one accessible <a href="6.doc.html#33916">(&#167;6.6)</a> member of the interface type that is a field named <i>Id</i>, then a compile-time error occurs.
<a name="33169"></a>
<li>Otherwise, <i>Q</i><code>.</code><i>Id</i> denotes the value of the field. The type of the expression <i>Q</i><code>.</code><i>Id</i> is the declared type of the field. If <i>Q</i><code>.</code><i>Id</i> appears in a context that requires a variable and not a value, then a compile-time error occurs.
</ul>
<a name="22165"></a>
<li>If <i>Q</i> is an expression name, let <i>T</i> be the type of the expression <i>Q</i>:
<ul>
<a name="22169"></a>
<li>If <i>T</i> is not a reference type, a compile-time error occurs.
<a name="33185"></a>
<li>If there is not exactly one accessible <a href="6.doc.html#33916">(&#167;6.6)</a> member of the type <i>T</i> that is a field named <i>Id</i>, then a compile-time error occurs.
<a name="22170"></a>
<li>Otherwise, if this field is any of the following:
<ul>
<a name="33204"></a>
<li>A field of an interface type
<a name="33205"></a>
<li>A <code>final</code> field of a class type (which may be either a class variable or an instance variable)
<a name="33208"></a>
<li>The <code>final</code> field <code>length</code> of an array type
</ul>
<a name="33211"></a>
<li>then <i>Q</i><code>.</code><i>Id</i> denotes the value of the field. The type of the expression <i>Q</i><code>.</code><i>Id</i> is the declared type of the field. If <i>Q</i><code>.</code><i>Id</i> appears in a context that requires a variable and not a value, then a compile-time error occurs.
<a name="22173"></a>
<li>Otherwise, <i>Q</i><code>.</code><i>Id</i> denotes a variable, the field <i>Id</i> of class <i>T</i>, which may be either a class variable or an instance variable. The type of the expression <i>Q</i><code>.</code><i>Id</i> is the declared type of the field
</ul>
</ul><a name="62391"></a>
The example:
<p><pre><a name="22175"></a>
class Point {
<a name="22176"></a>	int x, y;
<a name="22177"></a>	static int nPoints;
<a name="22178"></a>}
<a name="22179"></a>
class Test {
<a name="22180"></a>	public static void main(String[] args) {
<a name="22181"></a>		int i = 0;
<a name="22182"></a>		i.x++;								// compile-time error
<a name="22183"></a>		Point p = new Point();
<a name="22184"></a>		p.nPoints();								// compile-time error
<a name="22185"></a>	}
<a name="22186"></a>}
</pre><a name="22187"></a>
encounters two compile-time errors, because the <code>int</code> variable <code>i</code> has no members, 
and because <code>nPoints</code> is not a method of class <code>Point</code>.
<p><a name="21652"></a>
<h3>6.5.6    Meaning of Method Names</h3>
<a name="32771"></a>
A <i>MethodName</i> can appear only in a method invocation expression <a href="15.doc.html#20448">(&#167;15.11)</a>. The 
meaning of a name classified as a <i>MethodName</i> is determined as follows.
<p><a name="54512"></a>
<h4>6.5.6.1    Simple Method Names</h4>
<a name="54513"></a>
If a method name consists of a single <i>Identifier</i>, then <i>Identifier</i> is the method name 
to be used for method invocation. The <i>Identifier</i> must name at least one method of 
the class or interface within whose declaration the <i>Identifier</i> appears. See <a href="15.doc.html#20448">&#167;15.11</a> 
for further discussion of the interpretation of simple method names in method 
invocation expressions.
<p><a name="54547"></a>
<h4>6.5.6.2    Qualified Method Names</h4>
<a name="33243"></a>
If a method name is of the form <i>Q</i><code>.</code><i>Id</i>, then <i>Q</i> has already been classified as a 
package name, a type name, or an expression name. If <i>Q</i> is a package name, then a 
compile-time error occurs. Otherwise, <i>Id</i> is the method name to be used for 
method invocation. If <i>Q</i> is a type name, then <i>Id</i> must name at least one <code>static</code> 
method of the type <i>Q</i>. If <i>Q</i> is an expression name, then let <i>T</i> be the type of the 
expression <i>Q</i>; <i>Id</i> must name at least one method of the type <i>T</i>. See <a href="15.doc.html#20448">&#167;15.11</a> for further
discussion of the interpretation of qualified method names in method invocation
expressions.
<p><a name="33916"></a>
<h2>6.6    Qualified Names and Access Control</h2>
<a name="33917"></a>
Qualified names are a means of access to members of packages and reference 
types; related means of access include field access expressions <a href="15.doc.html#41267">(&#167;15.10)</a> and 
method invocation expressions <a href="15.doc.html#20448">(&#167;15.11)</a>. All three are syntactically similar in that 
a "<code>.</code>" token appears, preceded by some indication of a package, type, or expression
having a type and followed by an <i>Identifier</i> that names a member of the package
or type. These are collectively known as constructs for <i>qualified access</i>.
<p><a name="33924"></a>
Java provides mechanisms for <i>access control</i>, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class. Access control applies to qualified access and to the invocation of constructors by class instance creation expressions <a href="15.doc.html#41147">(&#167;15.8)</a>, explicit constructor invocations <a href="8.doc.html#78435">(&#167;8.6.5)</a>, and the method <code>newInstance</code> of class <code>Class</code> <a href="javalang.doc2.html#15088">(&#167;20.3.6)</a>.<p>
<a name="62634"></a>
If access is permitted, then the accessed entity is said to be <i>accessible</i>.<p>
<a name="62395"></a>
<h3>6.6.1    Determining Accessibility</h3>
<ul><a name="33934"></a>
<li>Whether a package is accessible is determined by the host system <a href="7.doc.html#37758">(&#167;7.2)</a>.
<a name="62409"></a>
<li>If a class or interface type is declared <code>public</code>, then it may be accessed by any Java code that can access the package in which it is declared. If a class or interface type is not declared <code>public</code>, then it may be accessed only from within the package in which it is declared.
<a name="62410"></a>
<li>A member (field or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
<ul>
<a name="62795"></a>
<li>If the member or constructor is declared <code>public</code>, then access is permitted. All members of interfaces are implicitly <code>public</code>.
<a name="62561"></a>
<li>Otherwise, if the member or constructor is declared <code>protected</code>, then access is permitted only when one of the following is true:
<ul><ul>
<a name="62562"></a>
<li>Access to the member or constructor occurs from within the package containing the class in which the <code>protected</code> member is declared.
<a name="62452"></a>
<li>Access occurs within a subclass of the class in which the <code>protected</code> member is declared, and the access is correct as described in <a href="6.doc.html#62587">&#167;6.6.2</a>.
</ul>
</ul><a name="62857"></a>
<li>Otherwise, if the member or constructor is declared <code>private</code>, then access is permitted only when it occurs from within the class in which it is declared.
<a name="62586"></a>
<li>Otherwise, we say there is default access, which is permitted only when the access occurs from within the package in which the type is declared.
</ul>
</ul><a name="62587"></a>
<h3>6.6.2    Details on <code>protected</code> Access</h3>
<a name="62638"></a>
A <code>protected</code> member or constructor of an object may be accessed from outside 
the package in which it is declared only by code that is responsible for the implementation
of that object. Let <i>C</i> be the class in which a <code>protected</code> member or constructor
is declared and let <i>S</i> be the subclass of <i>C</i> in whose declaration the use of 
the <code>protected</code> member or constructor occurs. Then:
<p><ul><a name="60602"></a>
<li>If an access is of a <code>protected</code> member (field or method), let <i>Id</i> be its name. Consider then the means of qualified access:
<ul>
<a name="33943"></a>
<li>If the access is by a field access expression of the form <code>super.</code><i>Id</i>, then the access is permitted.
<a name="33945"></a>
<li>If the access is by a qualified name <i>Q</i><code>.</code><i>Id</i>, where <i>Q</i> is a <i>TypeName</i>, then the access is permitted if and only if <i>Q</i> is <i>S</i> or a subclass of <i>S</i>.
<a name="33946"></a>
<li>If the access is by a qualified name <i>Q</i><code>.</code><i>Id</i>, where <i>Q</i> is an <i>ExpressionName</i>, then the access is permitted if and only if the type of the expression <i>Q</i> is <i>S</i> or a subclass of <i>S</i>.
<a name="33947"></a>
<li>If the access is by a field access expression <i>E</i><code>.</code><i>Id</i>, where <i>E</i> is a <i>Primary</i> expression, or by a method invocation expression <i>E</i><code>.</code><i>Id</i><code>(</code>. . .<code>)</code>, where <i>E</i> is a <i>Primary</i> expression, then the access is permitted if and only if the type of <i>E</i> is <i>S</i> or a subclass of <i>S</i>.
</ul>
<a name="60590"></a>
<li>Otherwise, if an access is of a <code>protected</code> constructor:
<ul>
<a name="60601"></a>
<li>If the access is by a superclass constructor invocation <code>super(</code>. . .<code>)</code>, then the access is permitted.
<a name="62811"></a>
<li>If the access is by a class instance creation expression <code>new</code> <i>T</i><code>(</code>. . .<code>)</code>, then the access is not permitted. (A <code>protected</code> constructor can be accessed by a class instance creation expression only from within the package in which it is defined.)
<a name="62828"></a>
<li>If the access is by an invocation of the method <code>newInstance</code> of class <code>Class</code> <a href="javalang.doc2.html#15088">(&#167;20.3.6)</a>, then the access is not permitted.
</ul>
</ul><a name="62666"></a>
<h3>6.6.3    An Example of Access Control</h3>
<a name="62647"></a>
For examples of access control, consider the two compilation units:
<p><pre><br><a name="33958"></a>package points;
<br><a name="33959"></a>class PointVec { Point[] vec; }
</pre><a name="33960"></a>
and:
<p><pre><br><a name="33961"></a>package points;
<br></pre><pre><a name="33962"></a>
public class Point {
<a name="33963"></a>	protected int x, y;
<a name="33964"></a>	public void move(int dx, int dy) { x += dx; y += dy; }
<a name="33965"></a>	public int getX() { return x; }
<a name="33966"></a>	public int getY() { return y; }
<a name="33967"></a>}
</pre><a name="33968"></a>
which declare two class types in the package <code>points</code>:
<p><ul><a name="33969"></a>
<li>The class type <code>PointVec</code> is not <code>public</code> and not part of the <code>public</code> interface of the package <code>points</code>, but rather can be used only by other classes in the package.
<a name="33970"></a>
<li>The class type <code>Point</code> is declared <code>public</code> and is available to other packages. It is part of the <code>public</code> interface of the package <code>points</code>.
<a name="33971"></a>
<li>The methods <code>move</code>, <code>getX</code>, and <code>getY</code> of the class <code>Point</code> are declared <code>public</code> and so are available to any Java code that uses an object of type <code>Point</code>.
<a name="33972"></a>
<li>The fields <code>x</code> and <code>y</code> are declared <code>protected</code> and are accessible outside the package <code>points</code> only in subclasses of class <code>Point,</code> and only when they are fields of objects that are being implemented by the code that is accessing them.
</ul><a name="33976"></a>
See <a href="6.doc.html#36191">&#167;6.6.7</a> for an example of how the <code>protected</code> access modifier limits access.
<p><a name="36060"></a>
<h3>6.6.4    Example: Access to <code>public</code> and Non-<code>public</code> Classes</h3>
<a name="36063"></a>
If a class lacks the <code>public</code> modifier, access to the class declaration is limited to 
the package in which it is declared <a href="6.doc.html#33916">(&#167;6.6)</a>. In the example:
<p><pre><br><a name="36076"></a>package points;
<br></pre><pre><a name="36077"></a>
public class Point {
<a name="36078"></a>	public int x, y;
<a name="36079"></a>	public void move(int dx, int dy) { x += dx; y += dy; }
<a name="36080"></a>}
<br><a name="36081"></a>
class PointList {
<a name="36082"></a>	Point next, prev;
<a name="36083"></a>}
</pre><a name="36084"></a>
two classes are declared in the compilation unit. The class <code>Point</code> is available outside
the package <code>points</code>, while the class <code>PointList</code> is available for access only 
within the package. Thus a compilation unit in another package can access 
<code>points.Point</code>, either by using its fully qualified name:
<p><pre><br><a name="36085"></a>package pointsUser;
<br></pre><pre><a name="36086"></a>
class Test {
<a name="36087"></a>	public static void main(String[] args) {
<a name="36088"></a>		points.Point p = new points.Point();
<a name="36089"></a>		System.out.println(p.x + " " + p.y);
<a name="36090"></a>	}
<a name="36091"></a>}
</pre><a name="36092"></a>
or by using a single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> that mentions the fully 
qualfied name, so that the simple name may be used thereafter:
<p><pre><br><a name="36096"></a>package pointsUser;
<br><br><a name="36097"></a>import points.Point;
<br></pre><pre><a name="36098"></a>
class Test {
<a name="36099"></a>	public static void main(String[] args) {
<a name="36100"></a>		Point p = new Point();
<a name="36101"></a>		System.out.println(p.x + " " + p.y);
<a name="36102"></a>	}
<a name="36103"></a>}
</pre><a name="36104"></a>
However, this compilation unit cannot use or import <code>points.PointList</code>, which 
is not declared <code>public</code> and is therefore inaccessible outside package <code>points</code>.
<p><a name="36154"></a>
<h3>6.6.5    Example: Default-Access Fields, Methods, and Constructors</h3>
<a name="36155"></a>
If none of the access modifiers <code>public</code>, <code>protected</code>, or <code>private</code> are specified, a 
class member or constructor is accessible throughout the package that contains the 
declaration of the class in which the class member is declared, but the class member
or constructor is not accessible in any other package. If a <code>public</code> class has a 
method or constructor with default access, then this method or constructor is not 
accessible to or inherited by a subclass declared outside this package.
<p><a name="60607"></a>
For example, if we have:<p>
<pre><br><a name="36156"></a>package points;
<br></pre><pre><a name="36157"></a>
public class Point {
<a name="36158"></a>	public int x, y;
<a name="36159"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<a name="61627"></a>	public void moveAlso(int dx, int dy) { move(dx, dy); }
<a name="36160"></a>}
</pre><a name="36161"></a>
then a subclass in another package may declare an unrelated <code>move</code> method, with 
the same signature <a href="8.doc.html#38649">(&#167;8.4.2)</a> and return type. Because the original <code>move</code> method is 
not accessible from package <code>morepoints</code>, <code>super</code> may not be used:
<p><pre><br><a name="36165"></a>package morepoints;
<br></pre><pre><a name="36166"></a>
public class PlusPoint extends points.Point {
<a name="36167"></a>	public void move(int dx, int dy) {
<a name="61624"></a>		super.move(dx, dy);								// compile-time error
<a name="36170"></a>		moveAlso(dx, dy);
<a name="61628"></a>	}
<a name="36171"></a>}
</pre><a name="61629"></a>
Because move of <code>Point</code> is not overridden by <code>move</code> in <code>PlusPoint</code>, the method 
<code>moveAlso</code> in <code>Point</code> never calls the method move in <code>PlusPoint</code>.
<p><a name="61639"></a>
Thus if you delete the <code>super.move</code> call from <code>PlusPoint</code> and execute the test program:<p>
<pre><a name="61642"></a>
import points.Point;
<a name="61643"></a>
import morepoints.PlusPoint;
<a name="61644"></a>
class Test {
<a name="61645"></a>
    public static void main(String[] args) {
<a name="61646"></a>        PlusPoint pp = new PlusPoint();
<a name="61647"></a>        pp.move(1, 1);
<a name="61648"></a>    }
<br><a name="61649"></a>}
</pre><a name="61640"></a>
it terminates normally. If move of <code>Point</code> were overridden by <code>move</code> in <code>PlusPoint</code>, 
then this program would recurse infinitely, until a <code>StackoverflowError</code> 
occurred.
<p><a name="36250"></a>
<h3>6.6.6    Example: <code>public</code> Fields, Methods, and Constructors</h3>
<a name="36251"></a>
A <code>public</code> class member or constructor is accessible throughout the package 
where it is declared and from any other package that has access to the package in 
which it is declared <a href="7.doc.html#13194">(&#167;7.4.4)</a>. For example, in the compilation unit:
<p><pre><br><a name="36180"></a>package points;
<br></pre><pre><a name="36181"></a>
public class Point {
<br><a name="36182"></a>	int x, y;
<br><a name="36183"></a>
	public void move(int dx, int dy) {
<a name="36184"></a>		x += dx; y += dy;
<a name="36185"></a>		moves++;
<a name="36186"></a>	}
<br><br><a name="36187"></a>	public static int moves = 0;
<br><a name="36188"></a>}
</pre><a name="36189"></a>
the <code>public</code> class <code>Point</code> has as <code>public</code> members the <code>move</code> method and the <code>moves</code> 
field. These <code>public</code> members are accessible to any other package that has access 
to package <code>points</code>. The fields <code>x</code> and <code>y</code> are not <code>public</code> and therefore are accessible 
only from within the package <code>points</code>.
<p><a name="36191"></a>
<h3>6.6.7    Example: <code>protected</code> Fields, Methods, and Constructors</h3>
<a name="36201"></a>
Consider this example, where the <code>point</code> package declares:
<p><pre><br><a name="36202"></a>package points;
<br></pre><pre><a name="36203"></a>
public class Point {
<br><a name="36322"></a>	protected int x, y;
<br><a name="36324"></a>
	void warp(threePoint.Point3d a) {
<a name="61672"></a>		if (a.z &gt; 0)						// compile-time error: cannot access a.z
<a name="61670"></a>			a.delta(this);
<a name="36332"></a>	}
<br><a name="36323"></a>}
</pre><a name="36204"></a>
and the <code>threePoint</code> package declares:
<p><pre><br><a name="36331"></a>package threePoint;
<br><br><a name="36205"></a>import points.Point;
<br></pre><pre><a name="36206"></a>
public class Point3d extends Point {
<br><a name="36315"></a>	protected int z;
<br><a name="36207"></a>
	public void delta(Point p) {
<a name="36295"></a>		p.x += this.x;						// compile-time error: cannot access p.x
<a name="36296"></a>		p.y += this.y;						// compile-time error: cannot access p.y
<a name="36297"></a>	}
<br><a name="36208"></a>
	public void delta3d(Point3d q) {
<a name="36300"></a>		q.x += this.x;
<a name="36317"></a>		q.y += this.y;
<a name="36319"></a>		q.z += this.z;
<a name="36302"></a>	}
<br><a name="36209"></a>}
</pre><a name="36210"></a>
which defines a class <code>Point3d</code>. A compile-time error occurs in the method <code>delta 
</code>here: it cannot access the protected members <code>x</code> and <code>y</code> of its parameter <code>p</code>, because 
while <code>Point3d</code> (the class in which the references to fields <code>x</code> and <code>y</code> occur) is a subclass
of <code>Point</code> (the class in which <code>x</code> and <code>y</code> are declared), it is not involved in the 
implementation of a <code>Point</code> (the type of the parameter <code>p</code>). The method <code>delta3d</code> 
can access the protected members of its parameter <code>q</code>, because the class <code>Point3d</code> is 
a subclass of <code>Point</code> and is involved in the implementation of a <code>Point3d</code>.
<p><a name="36214"></a>
The method <code>delta</code> could try to cast (<a href="5.doc.html#176921">&#167;5.4</a>, <a href="15.doc.html#238146">&#167;15.15</a>) its parameter to be a <code>Point3d</code>, but this cast would fail, causing an exception, if the class of <code>p</code> at run time were not <code>Point3d</code>.<p>
<a name="61715"></a>
A compile-time error also occurs in the method warp: it cannot access the protected member <code>z</code> of its parameter <code>a</code>, because while the class <code>Point</code> (the class in which the reference to field <code>z</code> occurs) is involved in the implementation of a <code>Point</code> (the type of the parameter a), it is not a subclass of <code>Point</code> (the class in which <code>z</code> is declared). <p>
<a name="36233"></a>
<h3>6.6.8    Example: <code>private</code> Fields, Methods, and Constructors</h3>
<a name="36235"></a>
<code>A</code> <code>private</code> class member or constructor is accessible only within the class body in 
which the member is declared and is not inherited by subclasses. In the example:
<p><pre><a name="36237"></a>
class Point {
<br><a name="36344"></a>	Point() { setMasterID(); }
<br><a name="36238"></a>
	int x, y;
<a name="36239"></a>	private int ID;
<a name="36240"></a>	private static int masterID = 0;
<br><a name="36241"></a>	private void setMasterID() { ID = masterID++; }
<br><a name="36242"></a>}
</pre><a name="36243"></a>
the <code>private</code> members <code>ID,</code> m<code>asterID</code>, and <code>setMasterID</code> may be used only 
within the body of class <code>Point</code>. They may not be accessed by qualified names, 
field access expressions, or method invocation expressions outside the body of the 
declaration of <code>Point</code>.
<p><a name="62528"></a>
See <a href="8.doc.html#16830">&#167;8.6.8</a> for an example that uses a <code>private</code> constructor.<p>
<a name="25430"></a>
<h2>6.7    Fully Qualified Names</h2>
<a name="24074"></a>
Every package, class, interface, array type, and primitive type has a fully qualified 
name. It follows that every type except the null type has a fully qualified name.
<p><ul><a name="9478"></a>
<li>The fully qualified name of a primitive type is the keyword for that primitive type, namely <code>boolean</code>, <code>char</code>, <code>byte</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>float</code>, or <code>double</code>.
<a name="33330"></a>
<li>The fully qualified name of a named package that is not a subpackage of a named package is its simple name.
<a name="33332"></a>
<li>The fully qualified name of a named package that is a subpackage of another named package consists of the fully qualified name of the containing package, followed by "<code>.</code>", followed by the simple (member) name of the subpackage.
<a name="28912"></a>
<li>The fully qualified name of a class or interface that is declared in an unnamed package is the simple name of the class or interface.
<a name="33340"></a>
<li>The fully qualified name of a class or interface that is declared in a named package consists of the fully qualified name of the package, followed by "<code>.</code>", followed by the simple name of the class or interface.
<a name="9454"></a>
<li>The fully qualified name of an array type consists of the fully qualified name of the component type of the array type followed by "<code>[]</code>".
</ul><a name="11162"></a>
Examples:
<p><ul><a name="12348"></a>
<li>The fully qualified name of the type <code>long</code> is "<code>long</code>".
<a name="12351"></a>
<li>The fully qualified name of the standard package <code>java.lang</code> is "<code>java.lang</code>" because it is subpackage <code>lang</code> of package <code>java</code>.
<a name="33392"></a>
<li>The fully qualified name of the class <code>Object</code>, which is defined in the package <code>java.lang</code>, is "<code>java.lang.Object</code>".
<a name="33394"></a>
<li>The fully qualified name of the interface <code>Enumeration</code>, which is defined in the package <code>java.util</code>, is "<code>java.util.Enumeration</code>".
<a name="33378"></a>
<li>The fully qualified name of the type "array of <code>double</code>" is "<code>double[]</code>".
<a name="33380"></a>
<li>The fully qualified name of the type "array of array of array of array of <code>String</code>" is "<code>java.lang.String[][][][]</code>".
</ul><a name="12352"></a>
In the example:
<p><pre><a name="12353"></a>package points;
</pre><pre><a name="12362"></a>
class Point { int x, y; }
<a name="12354"></a>
class PointVec {
<a name="12355"></a>	Point[] vec;
<a name="56765"></a>}
</pre><a name="56766"></a>
the fully qualified name of the type <code>Point</code> is "<code>points.Point</code>"; the fully qualified 
name of the type <code>PointVec</code> is "<code>points.PointVec</code>"; and the fully qualified name 
of the type of the field <code>vec</code> of class <code>PointVec</code> is "<code>points.Point[]</code>".
<p><a name="11186"></a>
<h2>6.8    Naming Conventions</h2>
<a name="9218"></a>
The Java system and standard classes attempt to use, whenever possible, names 
chosen according to the conventions presented here. These conventions help to 
make code more readable and avoid certain kinds of name conflicts.
<p><a name="34468"></a>
We recommend these conventions for use in all Java programs. However, these conventions should not be followed slavishly if long-held conventional usage dictates otherwise. So, for example, the <code>sin</code> and <code>cos</code> methods of the class <code>java.lang.Math</code> have mathematically conventional names, even though these method names flout Java convention because they are short and are not verbs.<p>
<a name="9184"></a>
<h3>6.8.1    Package Names</h3>
<a name="9253"></a>
Names of packages that are to be made widely available should be formed as 
described in <a href="7.doc.html#40169">&#167;7.7</a>. Such names are always qualified names whose first identifier 
consists of two or three uppercase letters that name an Internet domain, such as 
<code>COM</code>, <code>EDU</code>, <code>GOV</code>, <code>MIL</code>, <code>NET</code>, <code>ORG</code>, or a two-letter ISO country code such as <code>UK</code> or <code>JP</code>. 
Here are examples of hypothetical unique names that might be formed under this 
convention:
<p><pre><a name="9241"></a>
COM.JavaSoft.jag.Oak
<a name="9242"></a>ORG.NPR.pledge.driver
<a name="9252"></a>UK.ac.city.rugby.game
</pre><a name="32841"></a>
Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier <code>java</code>; package names that start with the identifier <code>java</code> are reserved to JavaSoft for naming standard Java packages.<p>
<a name="29469"></a>
When package names occur in expressions:<p>
<ul><a name="12971"></a>
<li>If a package name is hidden by a field declaration, then <code>import</code> declarations <a href="7.doc.html#26656">(&#167;7.5)</a> can usually be used to make available the type names declared in that package.
<a name="34379"></a>
<li>If a package name is hidden by a declaration of a parameter or local variable, then the name of the parameter or local variable can be changed without affecting other Java code.
<a name="34365"></a>
<li>The first component of a package name is normally not easily mistaken for a type name, as a type name normally begins with a single uppercase letter. (The Java language does not actually rely on case distinctions to determine whether a name is a package name or a type name. It is not possible for a type name to hide a package name.)
</ul><a name="29466"></a>
<h3>6.8.2    Class and Interface Type Names</h3>
<a name="32824"></a>
Names of class types should be descriptive nouns or noun phrases, not overly 
long, in mixed case with the first letter of each word capitalized. For example:
<p><pre><a name="9292"></a>
<code>ClassLoader
</code><a name="9298"></a><code>SecurityManager
</code><a name="9309"></a><code>Thread
</code><a name="9299"></a><code>Dictionary
</code><a name="9316"></a>BufferedInputStream
</pre><a name="9111"></a>
Likewise, names of interface types should be short and descriptive, not overly long, in mixed case with the first letter of each word capitalized. The name may be a descriptive noun or noun phrase, which is appropriate when an interface is used as if it were an abstract superclass, such as interfaces <code>java.io.DataInput</code> and <code>java.io.DataOutput</code>; or it may be an adjective describing a behavior, as for the interfaces <code>java.lang.Runnable</code> and <code>java.lang.Cloneable</code>.<p>
<a name="12992"></a>
Hiding involving class and interface type names is rare. Names of fields, parameters, and local variables normally do not hide type names because they conventionally begin with a lowercase letter whereas type names conventionally begin with an uppercase letter.<p>
<a name="9322"></a>
<h3>6.8.3    Method Names</h3>
<a name="34563"></a>
Method names should be verbs or verb phrases, in mixed case, with the first letter 
lowercase and the first letter of any subsequent words capitalized. Here are some 
additional specific conventions for method names:
<p><ul><a name="34587"></a>
<li>Methods to <code>get</code> and <code>set</code> an attribute that might be thought of as a variable <i>V</i> should be named <code>get</code><i>V</i> and <code>set</code><i>V</i>. An example is the methods <code>getPriority</code> <a href="javalang.doc18.html#2819">(&#167;20.20.22)</a> and <code>setPriority</code> <a href="javalang.doc18.html#14175">(&#167;20.20.23)</a> of class <code>java.lang.Thread</code>.
<a name="34594"></a>
<li>A method that returns the length of something should be named <code>length</code>, as in class <code>java.lang.String</code> <a href="javalang.doc11.html#13985">(&#167;20.12.11)</a>.
<a name="9341"></a>
<li>A method that tests a <code>boolean</code> condition <i>V</i> about an object should be named <code>is</code><i>V</i>. An example is the method <code>isInterrupted</code> of class <code>java.lang.Thread</code> <a href="javalang.doc18.html#29183">(&#167;20.20.32)</a>.
<a name="34650"></a>
<li>A method that converts its object to a particular format <i>F</i> should be named <code>to</code><i>F</i>. Examples are the method <code>toString</code> of class <code>java.lang.Object</code> <a href="javalang.doc1.html#1152">(&#167;20.1.2)</a> and the methods <code>toLocaleString</code> <a href="javautil.doc3.html#7495">(&#167;21.3.27)</a> and <code>toGMTString</code> <a href="javautil.doc3.html#7496">(&#167;21.3.28)</a> of class <code>java.util.Date</code>.
</ul><a name="34660"></a>
Whenever possible and appropriate, basing the names of methods in a new class 
on names in an existing class that is similar, especially a class from the standard 
Java Application Programming Interface classes, will make it easier to use.
<p><a name="9384"></a>
Method names cannot hide or be hidden by other names <a href="6.doc.html#21652">(&#167;6.5.6)</a>.<p>
<a name="9351"></a>
<h3>6.8.4    Field Names</h3>
<a name="32831"></a>
Names of fields that are not <code>final</code> should be in mixed case with a lowercase first 
letter and the first letters of subsequent words capitalized. Note that well-designed 
Java classes have very few <code>public</code> or <code>protected</code> fields, except for fields that are 
constants (<code>final</code> <code>static</code> fields) <a href="6.doc.html#9367">(&#167;6.8.5)</a>.
<p><a name="56830"></a>
Fields should have names that are nouns, noun phrases, or abbreviations for nouns. Examples of this convention are the fields <code>buf</code>, <code>pos</code>, and <code>count</code> of the class <code>java.io.ByteArrayInputStream</code> <a href="javaio.doc6.html#28355">(&#167;22.6)</a> and the field <code>bytesTransferred</code> of the class <code>java.io.InterruptedIOException</code> <a href="javaio.doc30.html#30212">(&#167;22.30.1)</a>.<p>
<a name="13055"></a>
Hiding involving field names is rare.<p>
<ul><a name="29526"></a>
<li>If a field name hides a package name, then an <code>import</code> declaration <a href="7.doc.html#26656">(&#167;7.5)</a> can usually be used to make available the type names declared in that package.
<a name="13069"></a>
<li>If a field name hides a type name, then a fully qualified name for the type can be used.
<a name="29539"></a>
<li>Field names cannot hide method names.
<a name="9539"></a>
<li>If a field name is hidden by a declaration of a parameter or local variable, then the name of the parameter or local variable can be changed without affecting other Java code.
</ul><a name="9367"></a>
<h3>6.8.5    Constant Names</h3>
<a name="9368"></a>
The names of constants in interface types should be, and <code>final</code> variables of class 
types may conventionally be, a sequence of one or more words, acronyms, or 
abbreviations, all uppercase, with components separated by underscore "<code>_</code>" characters.
Constant names should be descriptive and not unnecessarily abbreviated. 
Conventionally they may be any appropriate part of speech. Examples of names 
for constants include <code>MIN_VALUE</code>, <code>MAX_VALUE</code>, <code>MIN_RADIX</code>, and <code>MAX_RADIX</code> of the 
class <code>java.lang.Character</code>.
<p><a name="9563"></a>
A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:<p>
<pre><a name="9564"></a>
interface ProcessStates {
<a name="9565"></a>	int PS_RUNNING = 0;
<a name="9566"></a>	int PS_SUSPENDED = 1;
<a name="9568"></a>}
</pre><a name="13087"></a>
Hiding involving constant names is rare:
<p><ul><a name="9569"></a>
<li>Constant names should be longer than three letters, so that they do not hide the initial component of a unique package name.
<a name="62840"></a>
<li>Constant names normally have no lowercase letters, so they will not normally hide names of packages, types, or fields, whose names normally contain at least one lowercase letter.
<a name="62841"></a>
<li>Constant names cannot hide method names, because they are distinguished syntactically.
</ul><a name="62552"></a>
<h3>6.8.6    Local Variable and Parameter Names</h3>
<a name="9381"></a>
Local variable and parameter names should be short, yet meaningful. They are 
often short sequences of lowercase letters that are not words. For example:
<p><ul><a name="12405"></a>
<li>Acronyms, that is the first letter of a series of words, as in <code>cp</code> for a variable holding a reference to a <code>ColoredPoint</code>
<a name="12410"></a>
<li>Abbreviations, as in <code>buf</code> holding a pointer to a <code>buffer</code> of some kind
<a name="12434"></a>
<li>Mnemonic terms, organized in some way to aid memory and understanding, typically by using a set of local variables with conventional names patterned after the names of parameters to widely used classes. For example:
<ul>
<a name="12435"></a>
<li><code>in</code> and <code>out</code>, whenever some kind of input and output are involved, patterned after the fields of <code>java.lang.System</code>
<a name="12436"></a>
<li><code>off</code> and <code>len</code>, whenever an offset and length are involved, patterned after the parameters to the <code>read</code> and <code>write</code> methods of the interfaces <code>DataInput</code> and <code>DataOutput</code> of <code>java.io</code>
</ul>
</ul><a name="12367"></a>
One-character local variable or parameter names should be avoided, except for temporary and looping variables, or where a variable holds an undistinguished value of a type. Conventional one-character names are:<p>
<ul><a name="9148"></a>
<li><code>b</code> for a <code>byte</code>
<a name="9149"></a>
<li><code>c</code> for a <code>char</code>
<a name="12485"></a>
<li><code>d</code> for a <code>double</code>
<a name="9150"></a>
<li><code>e</code> for an <code>Exception</code>
<a name="12479"></a>
<li><code>f</code> for a <code>float</code>
<a name="9151"></a>
<li><code>i</code>, <code>j</code>, and <code>k</code> for integers
<a name="12846"></a>
<li><code>l</code> for a <code>long</code>
<a name="9155"></a>
<li><code>o</code> for an <code>Object</code>
<a name="12475"></a>
<li><code>s</code> for a <code>String</code>
<a name="12474"></a>
<li><code>v</code> for an arbitrary value of some type
</ul><a name="34406"></a>
Local variable or parameter names that consist of only two or three uppercase letters should be avoided to avoid potential conflicts with the initial country codes and domain names that are the first component of unique package names <a href="7.doc.html#40169">(&#167;7.7)</a>.<p>
<a name="65318"></a>
<p>


<hr>
<!-- This inserts footnotes-->
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="5.doc.html">Prev</a> | <a href="7.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<p>
<font size=-1>Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)<br>
<i><a href="jcopyright.doc.html">Copyright &#169 1996 Sun Microsystems, Inc.</a>
All rights reserved</i>
<br>
Please send any comments or corrections via our <a href="http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback">feedback form</a>
</font>
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body></html><html>
<head>
<meta name="collection" content="exclude">

<title>The Java Language Specification
 Packages</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
 
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="6.doc.html">Prev</a> | <a href="8.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<hr><br>
 
<a name="34412"></a>
<p><strong>
CHAPTER
 7 </strong></p>
<a name="60384"></a>
<h1>Packages</h1>
<hr><p>
<a name="61541"></a>
Java programs are organized as sets of packages. Each package has its own set 
of names for types, which helps to prevent name conflicts. A type is accessible 
<a href="6.doc.html#33916">(&#167;6.6)</a> outside the package that declares it only if the type is declared <code>public</code>.
<p><a name="26517"></a>
The naming structure for packages is hierarchical <a href="7.doc.html#26535">(&#167;7.1)</a>. The members of a package are class and interface types <a href="7.doc.html#26783">(&#167;7.6)</a>, which are declared in compilation units of the package, and subpackages, which may contain compilation units and subpackages of their own.<p>
<a name="40294"></a>
A package can be stored in a file system <a href="7.doc.html#37546">(&#167;7.2.1)</a> or in a database <a href="7.doc.html#37739">(&#167;7.2.2)</a>. Packages that are stored in a file system have certain constraints on the organization of their compilation units to allow a simple implementation to find classes easily. In either case, the set of packages available to a Java program is determined by the host system, but must always include at least the three standard packages <code>java.lang</code>, <code>java.util</code>, and <code>java.io</code> as specified in Chapters <a href="javalang.doc.html#">20</a>, <a href="javautil.doc.html#">21</a>, and <a href="javaio.doc16.html#29544">22</a>. In most host environments, the standard packages <code>java.applet</code>, <code>java.awt</code>, and <code>java.net</code>, which are not described in this specification, are also available to Java programs.<p>
<a name="26522"></a>
A package consists of a number of compilation units <a href="7.doc.html#40031">(&#167;7.3)</a>. A compilation unit automatically has access to all types declared in its package and also automatically imports<i> </i>each of the types declared in the predefined package<i> </i><code>java.lang</code>.<p>
<a name="35454"></a>
A compilation unit has three parts, each of which is optional:<p>
<ul><a name="13571"></a>
<li>A <code>package</code> declaration <a href="7.doc.html#26619">(&#167;7.4)</a>, giving the fully qualified name <a href="6.doc.html#25430">(&#167;6.7)</a> of the package to which the compilation unit belongs
<a name="13599"></a>
<li><code>import</code> declarations <a href="7.doc.html#26656">(&#167;7.5)</a> that allow types from other packages to be referred to using their simple names
<a name="13606"></a>
<li>Type declarations <a href="7.doc.html#26783">(&#167;7.6)</a> of class and interface types
</ul><a name="26526"></a>
For small programs and casual development, a package can be unnamed <a href="7.doc.html#26639">(&#167;7.4.2)</a> or have a simple name, but if Java code is to be widely distributed, unique package names should be chosen <a href="7.doc.html#40169">(&#167;7.7)</a>. This can prevent the conflicts that would otherwise occur if two development groups happened to pick the same package name and these packages were later to be used in a single program.<p>
<a name="26535"></a>
<h2>7.1    Package Members</h2>
<a name="37172"></a>
A<i> package</i> can have members of either or both of the following kinds:
<p><ul><a name="29038"></a>
<li>Subpackages of the package
<a name="29031"></a>
<li>Types declared in the compilation units <a href="7.doc.html#40031">(&#167;7.3)</a> of the package
</ul><a name="37558"></a>
For example, in the standard Java Application Programming Interface:
<p><ul><a name="37559"></a>
<li>The package <code>java</code> has subpackages <code>awt</code>, <code>applet</code>, <code>io</code>, <code>lang</code>, <code>net</code>, and <code>util</code>, but no compilation units.
<a name="37560"></a>
<li>The package <code>java.awt</code> has a subpackage named <code>image</code>, as well as a number of compilation units containing declarations of class and interface types.
</ul><a name="13127"></a>
If the fully qualified name <a href="6.doc.html#25430">(&#167;6.7)</a> of a package is <i>P</i><i></i>, and <i>Q</i> is a subpackage of <i>P</i>, 
then <i>P</i><code>.</code><i>Q</i> is the fully qualified name of the subpackage.
<p><a name="37562"></a>
The subpackages of package <code>java</code> named <code>lang</code>, <code>util</code>, and <code>io</code> (whose fully qualified package names are therefore <code>java.lang</code>, <code>java.util</code>, and <code>java.io</code>) are a standard part of every Java implementation and are specified in Chapters <a href="javalang.doc.html#">20</a>, <a href="javautil.doc.html#">21</a>, and <a href="javaio.doc11.html#28749">22</a>. Many Java implementations will include the entire set of <code>java</code> packages defined in the series of books <i>The Java Application Programming Interface</i>.<p>
<a name="37573"></a>
A package may not contain a type declaration and a subpackage of the same name, or a compile-time error results. Here are some examples:<p>
<ul><a name="37575"></a>
<li>Because the package <code>java.awt</code> has a subpackage <code>image</code>, it cannot (and does not) contain a declaration of a class or interface type named <code>image</code>.
<a name="37576"></a>
<li>If there is a package named <code>mouse</code> and a type <code>Button</code> in that package (which then might be referred to as <code>mouse.Button</code>), then there cannot be any package with the fully qualified name <code>mouse.Button</code> or <code>mouse.Button.Click</code>.
<a name="61007"></a>
<li>If <code>COM.Sun.java.jag</code> is the fully qualified name of a type, then there cannot be any package whose fully qualified name is either <code>COM.Sun.java.jag</code> or <code>COM.Sun.java.jag.scrabble</code>.
</ul><a name="61009"></a>
The hierarchical naming structure for packages is intended to be convenient for organizing related packages in a conventional manner, but has no significance in the Java language itself other than the prohibition against a package having a subpackage with the same simple name as a type declared in that package. There is no special access relationship in the Java language between a package named <code>oliver</code> and another package named <code>oliver.twist</code>, or between packages named <code>evelyn.wood</code> and <code>evelyn.Waugh</code>. For example, the code in a package named <code>oliver.twist</code> has no better access to the types declared within package <code>oliver</code> than code in any other package.<p>
<a name="37758"></a>
<h2>7.2    Host Support for Packages</h2>
<a name="37780"></a>
Each Java host determines how packages, compilation units, and subpackages are 
created and stored; which top-level package names are in scope in a particular 
compilation; and which packages are accessible.
<p><a name="37759"></a>
The packages may be stored in a local file system in simple implementations of Java. Other implementations may use a distributed file system or some form of database to store Java source and/or binary code.<p>
<a name="37546"></a>
<h3>7.2.1    Storing Packages in a File System</h3>
<a name="37463"></a>
As an extremely simple example, all the Java packages and source and binary 
code on a system might be stored in a single directory and its subdirectories. Each 
immediate subdirectory of this directory would represent a top-level package, that 
is, one whose fully qualified name consists of a single simple name. The directory 
might contain the following immediate subdirectories:
<p><pre><a name="37473"></a>
COM
<a name="13211"></a>gls
<a name="13212"></a>jag
<a name="13213"></a>java
<a name="13214"></a>wnj
</pre><a name="37477"></a>
where directory <code>java</code> would contain the standard Java Application Programming 
Interface packages that are part of every standard Java system; the directories <code>jag</code>, 
<code>gls</code>, and <code>wnj</code> might contain packages that the three authors of this specification 
created for their personal use and to share with each other within this small group; 
and the directory <code>COM</code> would contain packages procured from companies that used 
the conventions described in <a href="7.doc.html#40169">&#167;7.7</a> to generate unique names for their packages.
<p><a name="37480"></a>
Continuing the example, the directory <code>java</code> would probably contain at least the following subdirectories:<p>
<pre><a name="37481"></a>
applet	
<a name="13215"></a>awt
<a name="13216"></a>io
<a name="13217"></a>lang
<a name="13218"></a>net
<a name="13219"></a>util
</pre><a name="37490"></a>
corresponding to the standard packages <code>java.applet</code>, <code>java.awt</code>, <code>java.io</code>, 
<code>java.lang</code>, <code>java.net</code>, and <code>java.util</code> that are defined as part of the standard 
Java Application Programming Interface.
<p><a name="37491"></a>
Still continuing the example, if we were to look inside the directory <code>util</code>, we might see the following files:<p>
<pre><a name="37492"></a>
BitSet.java										Observable.java
<a name="37493"></a>BitSet.class										Observable.class
<a name="37494"></a>Date.java										Observer.java
<a name="37495"></a>Date.class										Observer.class
<a name="37496"></a>Dictionary.java										Properties.java
<a name="37497"></a>Dictionary.class										Properties.class
<a name="37500"></a>EmptyStackException.java										Random.java
<a name="37501"></a>EmptyStackException.class										Random.class
<a name="37502"></a>Enumeration.java										Stack.java
<a name="37503"></a>Enumeration.class										Stack.class
<a name="37504"></a>Hashtable.java										StringTokenizer.java
<a name="37505"></a>Hashtable.class										StringTokenizer.class
<a name="37506"></a>NoSuchElementException.java										Vector.java
<a name="37507"></a>NoSuchElementException.class										Vector.class
</pre><a name="37466"></a>
where each of the <code>.java</code> files contains the source for a compilation unit <a href="7.doc.html#40031">(&#167;7.3)</a> 
that contains the definition of a class or interface whose binary compiled form is 
contained in the corresponding <code>.class</code> file.
<p><a name="37599"></a>
Under this simple organization of packages, an implementation of Java would transform a package name into a pathname by concatenating the components of the package name, placing a file name separator (directory indicator) between adjacent components. For example, if this simple organization were used on a UNIX system, where the file name separator is <code>/</code>, the package name:<p>
<pre><a name="37600"></a>jag.scrabble.board
</pre><a name="37601"></a>
would be transformed into the directory name:
<p><pre><a name="37602"></a>jag/scrabble/board
</pre><a name="37603"></a>
and:
<p><pre><a name="37604"></a>COM.Sun.sunsoft.DOE
</pre><a name="37605"></a>
would be transformed to the directory name:
<p><pre><a name="37606"></a><code>COM/Sun/sunsoft/DOE
</code></pre><a name="37608"></a>
In fact, the standard JavaSoft Java Developer's Kit on UNIX differs from the very simple discipline described here only in that it provides a <code>CLASSPATH</code> environment variable that specifies a set of directories, each of which is treated like the single directory described here. These directories are searched in order for definitions of named packages and types.<p>
<a name="37709"></a>
A package name component or class name might contain a character that cannot correctly appear in a host file system's ordinary directory name, such as a Unicode character on a system that allows only ASCII characters in file names. As a convention, the character can be escaped by using, say, the <code>@</code> character followed by four hexadecimal digits giving the numeric value of the character, as in the <code>\u</code><i>xxxx</i> escape <a href="3.doc.html#100850">(&#167;3.3)</a>, so that the package name:<p>
<pre><a name="37613"></a>children.activities.crafts.papierM\u00e2ch\u00e9
</pre><a name="37614"></a>
which can also be written using full Unicode as:
<p><pre><a name="37615"></a>children.activities.crafts.papierM&acirc;ch&eacute;
</pre><a name="37616"></a>
might be mapped to the directory name:
<p><pre><a name="37617"></a>children/activities/crafts/papierM@00e2ch@00e9
</pre><a name="37618"></a>
If the <code>@</code> character is not a valid character in a file name for some given host file 
system, then some other character that is not valid in a Java identifier could be 
used instead.
<p><a name="37739"></a>
<h3>7.2.2    Storing Packages in a Database</h3>
<a name="37740"></a>
A host system may store packages and their compilation units and subpackages in 
a database.
<p><a name="35013"></a>
Java allows such a database to relax the restrictions <a href="7.doc.html#26783">(&#167;7.6)</a> on compilation units in file-based implementations. For example, a system that uses a database to store packages need not enforce a maximum of one <code>public</code> class or interface per compilation unit. Systems that use a database must, however, provide an option to convert a Java program to a form that obeys the restrictions, for purposes of export to file-based implementations.<p>
<a name="40031"></a>
<h2>7.3    Compilation Units</h2>
<a name="26594"></a>
<i>CompilationUnit </i>is the goal symbol <a href="2.doc.html#40415">(&#167;2.1)</a> for the syntactic grammar <a href="2.doc.html#140845">(&#167;2.3)</a> of 
Java programs. It is defined by the following productions:
<p><ul><pre>
<i>CompilationUnit:<br>
	PackageDeclaration</i><sub><i>opt</i></sub><code> </code><i>ImportDeclarations</i><sub><i>opt</i></sub><code> </code><i>TypeDeclarations</i><sub><i>opt
</i></sub>
<i>ImportDeclarations:<br>
</i>	<i>ImportDeclaration<br>
</i>	<i>ImportDeclarations</i><code> </code><i>ImportDeclaration
</i>
<i>TypeDeclarations:<br>
</i>	<i>TypeDeclaration<br>
</i>	<i>TypeDeclarations</i><code> </code><i>TypeDeclaration
</i></pre></ul><a name="24124"></a>
Types declared in different compilation units can depend on each other, circularly. 
A Java compiler must arrange to compile all such types at the same time.
<p><a name="35022"></a>
A <i>compilation unit</i> consists of three parts, each of which is optional:<p>
<ul><a name="35029"></a>
<li>A <code>package</code> declaration <a href="7.doc.html#26619">(&#167;7.4)</a>, giving the fully qualified name <a href="6.doc.html#25430">(&#167;6.7)</a> of the package to which the compilation unit belongs
<a name="35033"></a>
<li><code>import</code> declarations <a href="7.doc.html#26656">(&#167;7.5)</a> that allow types from other packages to be referred to using their simple names
<a name="35037"></a>
<li>Type declarations <a href="7.doc.html#26783">(&#167;7.6)</a> of class and interface types
</ul><a name="26614"></a>
Every compilation unit automatically and implicitly imports every <code>public</code> type name declared in the predefined package <code>java.lang</code>, so that the names of all those types are available as simple names, as described in <a href="7.doc.html#26741">&#167;7.5.3</a>.<p>
<a name="26619"></a>
<h2>7.4    Package Declarations</h2>
<a name="35052"></a>
A package declaration appears within a compilation unit to indicate the package 
to which the compilation unit belongs. A compilation unit that has no package 
declaration is part of an unnamed package.
<p><a name="26621"></a>
<h3>7.4.1    Named Packages</h3>
<a name="26626"></a>
A <i>package declaration</i> in a compilation unit specifies the name <a href="6.doc.html#31692">(&#167;6.2)</a> of the package
to which the compilation unit belongs.
<p><ul><pre>
<i>PackageDeclaration:<br>
	</i><code>package </code><i>PackageName</i><code> ;
</code></pre></ul><a name="26629"></a>
The package name mentioned in a package declaration must be the fully qualified 
name <a href="6.doc.html#25430">(&#167;6.7)</a> of the package.
<p><a name="26630"></a>
If a type named <i>T</i><em></em> is declared in a compilation unit of a package whose fully qualified name is <i>P</i>, then the fully qualified name of the type is <i>P</i><code>.</code><i>T</i>; thus in the example:<p>
<pre><a name="26635"></a>package wnj.points;
<a name="26636"></a>class Point { int x, y; }
</pre><a name="26637"></a>
the fully qualified name of class <code>Point</code> is <code>wnj.points.Point</code>. 
<p><a name="26639"></a>
<h3>7.4.2    Unnamed Packages</h3>
<a name="26640"></a>
A compilation unit that has no package declaration is part of an unnamed package. 
As an example, the compilation unit:
<p><pre><a name="35107"></a>
class FirstCall {
<a name="35108"></a>	public static void main(String[] args) {
<a name="35110"></a>		System.out.println("Mr. Watson, come here. "
<a name="35111"></a>									+ "I want you.");
<a name="35112"></a>	}
<a name="35113"></a>}
</pre><a name="35114"></a>
defines a very simple compilation unit as part of an unnamed package.
<p><a name="26641"></a>
A Java system must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.<p>
<a name="35086"></a>
In Java systems that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is available at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system.<p>
<a name="35134"></a>
Unnamed packages are provided by Java principally for convenience when developing small or temporary applications or when just beginning development.<p>
<a name="37842"></a>
Caution must be taken when using unnamed packages. It is possible for a compilation unit in a named package to import a type from an unnamed package, but the compiled version of this compilation unit will likely then work only when that particular unnamed package is "current." For this reason, it is strongly recommended that compilation units of named packages never import types from unnamed packages. It is also recommended that any type declared in an unnamed package not be declared <code>public</code>, to keep them from accidentally being imported by a named package.<p>
<a name="35133"></a>
It is recommended that a Java system provide safeguards against unintended consequences in situations where compilation units of named packages import types from unnamed packages. One strategy is to provide a way to associate with each named package at most one unnamed package, and then to detect and warn about situations in which a named package is used by more than one unnamed package. It is specifically not required-indeed, it is strongly discouraged-for an implementation to support use of a named package by more than one unnamed package by maintaining multiple compiled versions of the named package.<p>
<a name="13180"></a>
<h3>7.4.3    Scope and Hiding of a Package Name</h3>
<a name="13187"></a>
Which top-level package names are in scope (<a href="6.doc.html#33623">&#167;6.3</a>, <a href="6.doc.html#20569">&#167;6.5</a>) is determined by conventions
of the host system.
<p><a name="35593"></a>
Package names never hide other names.<p>
<a name="13194"></a>
<h3>7.4.4    Access to Members of a Package</h3>
<a name="13195"></a>
Whether access to members of a package is allowed is determined by the host system.
The package <code>java</code> should always be accessible, and its standard subpackages 
<code>lang</code>, <code>io</code>, and <code>util</code> should always be accessible.
<p><a name="13244"></a>
It is strongly recommended that the protections of a file system or database used to store Java programs be set to make all compilation units of a package available whenever any of the compilation units is available.<p>
<a name="26656"></a>
<h2>7.5    Import Declarations</h2>
<a name="26658"></a>
An <i>import declaration</i> allows a type declared in another package to be referred to 
by a simple name <a href="6.doc.html#31692">(&#167;6.2)</a> that consists of a single identifier. Without the use of an 
appropriate <code>import</code> declaration, the only way to refer to a type declared in another 
package is to use its fully qualified name <a href="6.doc.html#25430">(&#167;6.7)</a>.
<p><ul><pre>
<i>ImportDeclaration:<br>
</i>	<i>SingleTypeImportDeclaration<br>
</i>	<i>TypeImportOnDemandDeclaration
</i></pre></ul><a name="37962"></a>
A single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> imports a single type, by mentioning its fully qualified name. A type-import-on-demand declaration <a href="7.doc.html#26725">(&#167;7.5.2)</a> imports all the <code>public</code> types of a named package as needed.<p>
<a name="37929"></a>
An <code>import</code> declaration makes types available by their simple names only within the compilation unit that actually contains the <code>import</code> declaration. The scope of the name(s) it introduces specifically does not include the <code>package</code> statement, other <code>import</code> statements in the current compilation unit, or other compilation units in the same package. Please see <a href="7.doc.html#24151">&#167;7.5.4</a> for an illustrative example.<p>
<a name="26699"></a>
<h3>7.5.1    Single-Type-Import Declaration</h3>
<a name="13275"></a>
A <i>single-type-import declaration </i>imports a single type by giving its fully qualified 
name, making it available under a simple name in the class and interface declarations
of its compilation unit.
<p><ul><pre>
<i>SingleTypeImportDeclaration:<br>
</i><code>	import </code><i>TypeName</i><code> ;
</code></pre></ul><a name="29086"></a>
The <i>TypeName</i> must be the fully qualified name of a class or interface type; a 
compile-time error occurs if the named type does not exist. If the named type is 
not in the current package, then it must be accessible <a href="6.doc.html#33916">(&#167;6.6)</a>-in an accessible 
package and declared <code>public</code> (<a href="8.doc.html#21613">&#167;8.1.2</a>, <a href="9.doc.html#235947">&#167;9.1.2</a>)-or a compile-time error occurs.
<p><a name="37971"></a>
The example:<p>
<pre><a name="26702"></a>import java.util.Vector;
</pre><a name="45771"></a>
causes the simple name <code>Vector</code> to be available within the class and interface declarations
in a compilation unit. Thus, the simple name <code>Vector</code> refers to the type 
<code>Vector</code> in the package <code>java.util</code> in all places where it is not hidden <a href="6.doc.html#33623">(&#167;6.3)</a> by a 
declaration of a field, parameter, or local variable with the same name.
<p><a name="29151"></a>
If two single-type-import declarations in the same compilation unit attempt to import types with the same simple name, then a compile-time error occurs, unless the two types are the same type, in which case the duplicate declaration is ignored. If another type with the same name is otherwise declared in the current compilation unit except by a type-import-on-demand declaration <a href="7.doc.html#26725">(&#167;7.5.2)</a>, then a compile-time error occurs. <p>
<a name="29134"></a>
So the sample program:<p>
<pre><br><a name="29135"></a>import java.util.Vector;
<br><a name="29136"></a>class Vector { Object[] vec; }
</pre><a name="29137"></a>
causes a compile-time error because of the duplicate declaration of <code>Vector</code>, as 
does:
<p><pre><br><a name="29138"></a>import java.util.Vector;
<br><a name="29139"></a>import myVector.Vector;
</pre><a name="29140"></a>
where <code>myVector</code> is a package containing the compilation unit:
<p><pre><br><a name="29141"></a>package myVector;
<br><a name="29142"></a>public class Vector { Object[] vec; }
</pre><a name="29113"></a>
The compiler keeps track of types by their fully qualified names <a href="6.doc.html#25430">(&#167;6.7)</a>. Simple names and fully qualified names may be used interchangeably whenever they are both available.<p>
<a name="60471"></a>
Note that an import statement cannot import a subpackage, only a type. For example, it does not work to try to import <code>java.util</code> and then use the name <code>util.Random</code> to refer to the type <code>java.util.Random</code>:<p>
<pre><br><a name="60474"></a>import java.util;										// incorrect: compile-time error
<br><a name="60475"></a>class Test { util.Random generator; }
</pre><a name="26725"></a>
<h3>7.5.2    Type-Import-on-Demand Declaration</h3>
<a name="26727"></a>
A <i>type-import-on-demand declaration</i> allows all <code>public</code> types declared in the 
package named by a fully qualified name to be imported as needed.
<p><ul><pre>
<i>TypeImportOnDemandDeclaration:<br>
	</i><code>import </code><i>PackageName</i><code> . * ;
</code></pre></ul><a name="29163"></a>
It is a compile-time error for a type-import-on-demand declaration to name a 
package that is not accessible <a href="6.doc.html#33916">(&#167;6.6)</a>, as determined by the host system <a href="7.doc.html#37758">(&#167;7.2)</a>. 
Two or more type-import-on-demand declarations in the same compilation unit 
may name the same package; the effect is as if there were exactly one such declaration.
It is not a compile-time error to name the current package or <code>java.lang</code> in 
a type-import-on-demand declaration, even though they are already imported; the 
duplicate type-import-on-demand declaration is ignored.
<p><a name="35214"></a>
The example:<p>
<pre><a name="35215"></a>import java.util.*;
</pre><a name="35216"></a>
causes the simple names of all <code>public</code> types declared in the package <code>java.util</code> 
to be available within the class and interface declarations of the compilation unit. 
Thus, the simple name <code>Vector</code> refers to the type <code>Vector</code> in the package 
<code>java.util</code> in all places where it is not hidden <a href="6.doc.html#33623">(&#167;6.3)</a> by a single-type-import declaration
of a type whose simple name is <code>Vector</code>; by a type named <code>Vector</code> and 
declared in the package to which the compilation unit belongs; or by a declaration 
of a field, parameter, or local variable named <code>Vector</code>. (It would be unusual for any 
of these conditions to occur.)
<p><a name="26741"></a>
<h3>7.5.3    Automatic Imports</h3>
<a name="26743"></a>
Each compilation unit automatically imports each of the<i> </i><code>public</code><i> </i>type names 
declared in the predefined package<i> </i><code>java.lang</code>, as if the declaration:
<p><pre><a name="26744"></a>import java.lang.*;
</pre><a name="26745"></a>
appeared at the beginning of each compilation unit, immediately following any 
<code>package</code> statement.
<p><a name="26749"></a>
The full specification of <code>java.lang</code> is given in Chapter <a href="javalang.doc.html#">20</a>. The following <code>public</code> types are defined in <code>java.lang</code>:<p>
<pre><a name="26750"></a>
AbstractMethodError										LinkageError
<a name="26751"></a>ArithmeticException										Long
<a name="26753"></a>ArrayStoreException										Math
<a name="35299"></a>Boolean										NegativeArraySizeException
<a name="35300"></a>Character										NoClassDefFoundError
<a name="35301"></a>Class										NoSuchFieldError
<a name="35302"></a>ClassCastException										NoSuchMethodError
<a name="26758"></a>ClassCircularityError										NullPointerException
<a name="61567"></a>ClassFormatError										Number
<a name="61568"></a>ClassLoader										NumberFormatException
<a name="61569"></a>ClassNotFoundException										Object
<a name="26762"></a>CloneNotSupportedException										OutOfMemoryError
<a name="26763"></a>Cloneable										Process
<a name="26764"></a>Compiler										Runnable
<a name="26765"></a>Double										Runtime
<a name="26766"></a>Error										RuntimeException
<a name="26767"></a>Exception										SecurityException
<a name="34240"></a>ExceptionInInitializerError										SecurityManager
<a name="35238"></a>Float										StackOverflowError
<a name="35239"></a>IllegalAccessError										String
<a name="35240"></a>IllegalAccessException										StringBuffer
<a name="26771"></a>IllegalArgumentException										System
<a name="61639"></a>IllegalMonitorStateException										Thread
<a name="61640"></a>IllegalThreadStateException										ThreadDeath
<a name="61641"></a>IncompatibleClassChangeError										ThreadGroup
<a name="61634"></a>IndexOutOfBoundsException										Throwable
<a name="26776"></a>InstantiationError										UnknownError
<a name="26777"></a>InstantiationException										UnsatisfiedLinkError
<a name="26778"></a>Integer										VerifyError
<a name="26779"></a>InternalError										VirtualMachineError
<a name="26780"></a>InterruptedException
</pre><a name="24151"></a>
<h3>7.5.4    A Strange Example</h3>
<a name="24152"></a>
Package names and type names are usually different under the naming conventions
described in <a href="6.doc.html#11186">&#167;6.8</a>. Nevertheless, in a contrived example where there is an 
unconventionally-named package <code>Vector</code>, which declares a <code>public</code> class named 
<code>Mosquito</code>:
<p><pre><br><a name="24156"></a>package Vector;
<br><a name="24157"></a>public class Mosquito { int capacity; }
</pre><a name="24158"></a>
and then the compilation unit:
<p><pre><br><a name="24159"></a>package strange.example;
<br><br><a name="35349"></a>import java.util.Vector;
<br><br><a name="24160"></a>import Vector.Mosquito;
<br></pre><pre><a name="24161"></a>
class Test {
<a name="24162"></a>	public static void main(String[] args) {
<a name="24163"></a>		System.out.println(new Vector().getClass());
<a name="24164"></a>		System.out.println(new Mosquito().getClass());
<a name="24165"></a>	}
<a name="24166"></a>}
</pre><a name="24170"></a>
the single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> importing class <code>Vector</code> from package 
<code>java.util</code> does not prevent the package name <code>Vector</code> from appearing and being 
correctly recognized in subsequent <code>import</code> declarations. The example compiles 
and produces the output:
<p><pre><a name="24171"></a>
class java.util.Vector
<a name="24172"></a>class Vector.Mosquito
</pre><a name="26783"></a>
<h2>7.6    Type Declarations</h2>
<a name="26790"></a>
A type declaration declares a class type <a href="8.doc.html#3857">(&#167;8)</a> or an interface type <a href="9.doc.html#238678">(&#167;9)</a>:
<p><ul><pre>
<i>TypeDeclaration:<br>
</i>	<i>ClassDeclaration<br>
</i>	<i>InterfaceDeclaration<br>
</i>	<code>;
</code></pre></ul><a name="61526"></a>
A Java compiler must ignore extra "<code>;</code>" tokens appearing at the level of type declarations. Stray semicolons are permitted in Java solely as a concession to C++ programmers who are used to writing:<p>
<pre><a name="61527"></a>class date { int month, day, year; };
</pre><a name="61528"></a>
(In C++, but not in Java, one can provide a comma-separated list of identifiers in 
order to declare variables between the "<code>}</code>" and the "<code>;</code>".) Extra semicolons should 
not be used in new Java code. Software that reformats Java code can delete them.
<p><a name="37662"></a>
By default, the types declared in a package are accessible only within the compilation units of that package, but a type may be declared to be <code>public</code> to grant access to the type from code in other packages (<a href="6.doc.html#33916">&#167;6.6</a>, <a href="8.doc.html#21613">&#167;8.1.2</a>, <a href="9.doc.html#235947">&#167;9.1.2</a>).<p>
<a name="26802"></a>
A Java implementation must keep track of types within packages by their fully qualified names <a href="6.doc.html#25430">(&#167;6.7)</a>. Multiple ways of naming a type must be expanded to fully qualified names to make sure that such names are understood as referring to the same type. For example, if a compilation unit contains the single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a>:<p>
<pre><a name="26806"></a>import java.util.Vector;
</pre><a name="26807"></a>
then within that compilation unit the simple name <code>Vector</code> and the fully qualified 
name <code>java.util.Vector</code> refer to the same type.
<p><a name="40154"></a>
When Java packages are stored in a file system <a href="7.doc.html#37546">(&#167;7.2.1)</a>, the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as <code>.java</code> or <code>.jav</code>) if either of the following is true:<p>
<ul><a name="40155"></a>
<li>The type is referred to by code in other compilation units of the package in which the type is declared.
<a name="40159"></a>
<li>The type is declared <code>public</code> (and therefore is potentially accessible from code in other packages).
</ul><a name="40156"></a>
This restriction implies that there must be at most one such type per compilation 
unit. This restriction makes it easy for a Java compiler and Java Virtual Machine 
to find a named class within a package; for example, the source code for a <code>public</code> 
type <code>wet.sprocket.Toad</code> would be found in a file <code>Toad.java</code> in the directory 
<code>wet/sprocket</code>, and the corresponding object code would be found in the file 
<code>Toad.class</code> in the same directory.
<p><a name="20150"></a>
When Java packages are stored in a database <a href="7.doc.html#37739">(&#167;7.2.2)</a>, the host system need not enforce such restrictions.<p>
<a name="40175"></a>
In practice, many Java programmers choose to put each class or interface type in its own compilation unit, whether or not it is <code>public</code> or is referred to by code in other compilation units.<p>
<a name="40169"></a>
<h2>7.7    Unique Package Names</h2>
<a name="37792"></a>
Developers should take steps to avoid the possibility of two published packages 
having the same name by choosing <i>unique package names</i> for packages that are 
widely distributed. This allows packages to be easily and automatically installed 
and catalogued. This section specifies a standard convention, not enforced by a 
Java compiler, for generating such unique package names. Java systems are 
encouraged to provide automatic support for converting a set of packages from 
local and casual package names to the unique name format described here.
<p><a name="37825"></a>
If unique package names are not used, then package name conflicts may arise far from the point of creation of either of the conflicting packages. This may create &#32;a situation that is difficult or impossible for the user or programmer to resolve. The class <code>ClassLoader</code> <a href="javalang.doc13.html#14462">(&#167;20.14)</a> of the standard Java Virtual Machine environment can be used to isolate packages with the same name from each other in those cases where the packages will have constrained interactions, but not in a way that is transparent to a na&iuml;ve Java program.<p>
<a name="26818"></a>
You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as <code>Sun.COM</code>. You then reverse this name, component by component, to obtain, in this example, <code>COM.Sun</code>, and use this as a prefix for your package names, using a convention developed within your organization to further administer package names.<p>
<a name="26819"></a>
Such a convention might specify that certain directory name components be division, department, project, machine, or login names. Some possible examples:<p>
<pre><a name="26820"></a>
COM.Sun.sunsoft.DOE
<a name="26821"></a>COM.Sun.java.jag.scrabble
<a name="26822"></a>COM.Apple.quicktime.v2
<a name="26823"></a>EDU.cmu.cs.bovik.cheese
<a name="26824"></a>GOV.whitehouse.socks.mousefinder
</pre><a name="26825"></a>
The first component of a unique package name is always written in all-uppercase 
ASCII letters and should be one of the top-level domain names, currently <code>COM</code>, 
<code>EDU</code>, <code>GOV</code>, <code>MIL</code>, <code>NET</code>, <code>ORG</code>, or one of the English two-letter codes identifying countries
as specified in ISO Standard 3166, 1981. For more information, refer to the 
documents stored at <code>ftp://rs.internic.net/rfc</code>, for example, <code>rfc920.txt</code> 
and <code>rfc1032.txt</code>.
<p><a name="26826"></a>
The name of a package is not meant to imply anything about where the package is stored within the Internet; for example, a package named <code>EDU.cmu.cs.bovik.cheese</code> is not necessarily obtainable from Internet address <code>cmu.EDU</code> or from <code>cs.cmu.EDU</code> or from <code>bovik.cs.cmu.EDU</code>. The Java convention for generating unique package names is merely a way to piggyback a package naming convention on top of an existing, widely known unique name registry instead of having to create a separate registry for Java package names.<p>
<a name="60426"></a>
If you need to get a new Internet domain name, you can get an application form from <code>ftp://ftp.internic.net</code> and submit the complete forms by E-mail to <code>domreg@internic.net</code>. To find out what the currently registered domain names are, you can <code>telnet</code> to <code>rs.internic.net</code> and use the <code>whois</code> facility.<p>


<hr>
<!-- This inserts footnotes-->
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="6.doc.html">Prev</a> | <a href="8.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<p>
<font size=-1>Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)<br>
<i><a href="jcopyright.doc.html">Copyright &#169 1996 Sun Microsystems, Inc.</a>
All rights reserved</i>
<br>
Please send any comments or corrections via our <a href="http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback">feedback form</a>
</font>
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body></html><html>
<head>
<meta name="collection" content="exclude">

<title>The Java Language Specification
 Classes</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
 
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="7.doc.html">Prev</a> | <a href="9.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<hr><br>
 
<a name="3857"></a>
<p><strong>
CHAPTER
 8 </strong></p>
<a name="44365"></a>
<h1>Classes</h1>
<hr><p>
<a name="228205"></a>
Class declarations define new reference types and describe how they are 
implemented <a href="8.doc.html#15372">(&#167;8.1)</a>.
<p><a name="228209"></a>
The name of a class has as its scope all type declarations in the package in which the class is declared <a href="8.doc.html#39196">(&#167;8.1.1)</a>. A class may be declared <code>abstract</code> <a href="8.doc.html#34944">(&#167;8.1.2.1)</a> and must be declared <code>abstract</code> if it is incompletely implemented; such a class cannot be instantiated, but can be extended by subclasses. A class may be declared <code>final</code> <a href="8.doc.html#54727">(&#167;8.1.2.2)</a>, in which case it cannot have subclasses. If a class is declared <code>public</code>, then it can be referred to from other packages.<p>
<a name="35674"></a>
Each class except <code>Object</code> is an extension of (that is, a subclass of) a single existing class <a href="8.doc.html#21723">(&#167;8.1.3)</a> and may implement interfaces <a href="8.doc.html#34031">(&#167;8.1.4)</a>.<p>
<a name="15689"></a>
The body of a class declares members (fields and methods), static initializers, and constructors <a href="8.doc.html#18988">(&#167;8.1.5)</a>. The scope of the name of a member is the entire declaration of the class to which the member belongs. Field, method, and constructor declarations may include the access modifiers <a href="6.doc.html#33916">(&#167;6.6)</a> <code>public</code>, <code>protected</code>, or <code>private</code>. The members of a class include both declared and inherited members <a href="8.doc.html#21831">(&#167;8.2)</a>. Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.<p>
<a name="15807"></a>
Field declarations <a href="8.doc.html#40898">(&#167;8.3)</a> describe class variables, which are incarnated once, and instance variables, which are freshly incarnated for each instance of the class. A field may be declared <code>final</code> <a href="8.doc.html#35962">(&#167;8.3.1.2)</a>, in which case it cannot be assigned to except as part of its declaration. Any field declaration may include an initializer; the declaration of a <code>final</code> field must include an initializer.<p>
<a name="35821"></a>
Method declarations <a href="8.doc.html#40420">(&#167;8.4)</a> describe code that may be invoked by method invocation expressions <a href="15.doc.html#20448">(&#167;15.11)</a>. A class method is invoked relative to the class type; an instance method is invoked with respect to some particular object that is an instance of the class type. A method whose declaration does not indicate how it is implemented must be declared <code>abstract</code>. A method may be declared <code>final</code> <a href="8.doc.html#11246">(&#167;8.4.3.3)</a>, in which case it cannot be hidden or overridden. A method may be implemented by platform-dependent <code>native</code> code <a href="8.doc.html#31125">(&#167;8.4.3.4)</a>. A <code>synchronized</code> method <a href="8.doc.html#55408">(&#167;8.4.3.5)</a> automatically locks an object before executing its body and automatically unlocks the object on return, as if by use of a <code>synchronized</code> statement <a href="14.doc.html#79287">(&#167;14.17)</a>, thus allowing its activities to be synchronized with those of other threads <a href="17.doc.html#26250">(&#167;17)</a>.<p>
<a name="227762"></a>
Method names may be overloaded <a href="8.doc.html#227768">(&#167;8.4.7)</a>.<p>
<a name="35837"></a>
Static initializers <a href="8.doc.html#39245">(&#167;8.5)</a> are blocks of executable code that may be used to help initialize a class when it is first loaded <a href="12.doc.html#44557">(&#167;12.4)</a>.<p>
<a name="35735"></a>
Constructors <a href="8.doc.html#41652">(&#167;8.6)</a> are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new class instances. Like methods, they may be overloaded <a href="8.doc.html#229266">(&#167;8.6.6)</a>.<p>
<a name="15372"></a>
<h2>8.1    Class Declaration</h2>
<a name="23643"></a>
A <i>class declaration</i> specifies a new reference type:
<p><ul><pre>
<i>ClassDeclaration:<br>
</i>	<i>ClassModifiers</i><sub><i>opt</i></sub><code> class </code><i>Identifier</i><code> </code><i>Super</i><sub><i>opt</i></sub><code> </code><i>Interfaces</i><sub><i>opt</i></sub><code> </code><i>ClassBody
</i></pre></ul><a name="29516"></a>
If a class is declared in a named package <a href="7.doc.html#26621">(&#167;7.4.1)</a> with fully qualified name <i>P</i> 
<a href="6.doc.html#25430">(&#167;6.7)</a>, then the class has the fully qualified name <i>P</i><code>.</code><i>Identifier</i>. If the class is in an 
unnamed package <a href="7.doc.html#26639">(&#167;7.4.2)</a>, then the class has the fully qualified name <i>Identifier</i>. 
In the example:
<p><pre><a name="29524"></a>class Point { int x, y; }
</pre><a name="29525"></a>
the class <code>Point</code> is declared in a compilation unit with no <code>package</code> statement, and 
thus <code>Point</code> is its fully qualified name, whereas in the example:
<p><pre><a name="29526"></a>
package vista;
<a name="29527"></a>class Point { int x, y; }
</pre><a name="29528"></a>
the fully qualified name of the class <code>Point</code> is <code>vista.Point</code>. (The package name 
<code>vista</code> is suitable for local or personal use; if the package were intended to be 
widely distributed, it would be better to give it a unique package name <a href="7.doc.html#40169">(&#167;7.7)</a>.)
<p><a name="77906"></a>
A compile-time error occurs if the <em>Identifier </em>naming a class appears as the name of any other class type or interface type declared in the same package <a href="7.doc.html#26783">(&#167;7.6)</a>.<p>
<a name="28418"></a>
A compile-time error occurs if the <i>Identifier</i> naming a class is also declared as a type by a single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> in the compilation unit <a href="7.doc.html#40031">(&#167;7.3)</a> containing the class declaration.<p>
<a name="227770"></a>
In the example:<p>
<pre><a name="18901"></a>
package test;
<br><a name="33758"></a>import java.util.Vector;
<br><a name="25534"></a>
class Point {
<a name="25538"></a>	int x, y;
<a name="244854"></a>}
<br><a name="244855"></a>
interface Point {											// compile-time error #1
<a name="244856"></a>	int getR();
<a name="244821"></a>	int getTheta();
<a name="25541"></a>}
<br><a name="18906"></a>class Vector { Point[] pts; }											// compile-time error #2
</pre><a name="22257"></a>
the first compile-time error is caused by the duplicate declaration of the name 
<code>Point</code> as both a <code>class</code> and an <code>interface</code> in the same package. A second error 
detected at compile time is the attempt to declare the name <code>Vector</code> both by a class 
type declaration and by a single-type-import declaration.
<p><a name="35887"></a>
Note, however, that it is not an error for the <i>Identifier</i> that names a class also to name a type that otherwise might be imported by a type-import-on-demand declaration <a href="7.doc.html#26725">(&#167;7.5.2)</a> in the compilation unit <a href="7.doc.html#40031">(&#167;7.3)</a> containing the class declaration. In the example:<p>
<pre><a name="35908"></a>
package test;
<br><a name="35909"></a>import java.util.*;
<br><a name="35917"></a>class Vector { Point[] pts; }											// not a compile-time error
</pre><a name="35926"></a>
the declaration of the class <code>Vector</code> is permitted even though there is also a class 
<code>java.util.Vector</code>. Within this compilation unit, the simple name <code>Vector</code> refers 
to the class <code>test.Vector</code>, not to <code>java.util.Vector</code> (which can still be referred 
to by code within the compilation unit, but only by its fully qualified name).
<p><a name="39196"></a>
<h3>8.1.1    Scope of a Class Type Name</h3>
<a name="39197"></a>
The <i>Identifier</i> in a class declaration specifies the name of the class. This class 
name has as its scope <a href="6.doc.html#33623">(&#167;6.3)</a> the entire package in which the class is declared. As 
an example, the compilation unit:
<p><pre><br><a name="16470"></a>package points;
<br></pre><pre><a name="16471"></a>
class Point {
<a name="16472"></a>	int x, y;									// coordinates
<a name="16473"></a>	PointColor color;									// color of this point
<a name="16474"></a>	Point next;									// next point with this color<br>
	static int nPoints;
<a name="16475"></a>}
<br><a name="16476"></a>
class PointColor {
<a name="16477"></a>	Point first;									// first point with this color
<a name="16478"></a>	PointColor(int color) {
<a name="228374"></a>		this.color = color;
<a name="228375"></a>	}
<a name="16479"></a>	private int color;									// color components
<a name="16480"></a>}
</pre><a name="16486"></a>
defines two classes that use each other in the declarations of their class members. 
Because the class type names <code>Point</code> and <code>PointColor</code> have the entire package 
<code>points</code>, including the entire current compilation unit, as their scope, this example 
compiles correctly-that is, forward reference is not a problem.
<p><a name="21613"></a>
<h3>8.1.2    Class Modifiers</h3>
<a name="54718"></a>
A class declaration may include <i>class modifiers</i>.
<p><ul><pre>
<i>ClassModifiers:<br>
	ClassModifier<br>
	ClassModifiers</i><code> </code><i>ClassModifier
</i>
<i>ClassModifier: one of<br>
	</i><code>public</code><i>&#32;</i><code>abstract&#32;final
</code></pre></ul><a name="14169"></a>
The access modifier <code>public</code> is discussed in <a href="6.doc.html#33916">&#167;6.6</a>. A compile-time error occurs if 
the same modifier appears more than once in a class declaration. If two or more 
class modifiers appear in a class declaration, then it is customary, though not 
required, that they appear in the order consistent with that shown above in the production
for <i>ClassModifier</i>.
<p><a name="34944"></a>
<h4>8.1.2.1    abstract Classes</h4>
<a name="20269"></a>
An <code>abstract</code> class is a class that is incomplete, or to be considered incomplete. 
Only <code>abstract</code> classes may have <code>abstract</code> methods (<a href="8.doc.html#34484">&#167;8.4.3.1</a>, <a href="9.doc.html#78651">&#167;9.4</a>), that is, 
methods that are declared but not yet implemented. If a class that is not <code>abstract</code> 
contains an <code>abstract</code> method, then a compile-time error occurs. A class has 
<code>abstract</code> methods if any of the following is true:
<p><ul><a name="36417"></a>
<li>It explicitly contains a declaration of an <code>abstract</code> method <a href="8.doc.html#78188">(&#167;8.4.3)</a>.
<a name="14240"></a>
<li>It inherits an <code>abstract</code> method from its direct superclass <a href="8.doc.html#21723">(&#167;8.1.3)</a>.
<a name="14247"></a>
<li>A direct superinterface (<a href="8.doc.html#34031">&#167;8.1.4</a>) of the class declares or inherits a method (which is therefore necessarily <code>abstract</code>) and the class neither declares nor inherits a method that implements it.
</ul><a name="54865"></a>
In the example:
<p><pre><a name="54866"></a>
abstract class Point {
<a name="54867"></a>	int x = 1, y = 1;
<a name="54868"></a>	void move(int dx, int dy) {
<a name="54869"></a>		x += dx;
<a name="54870"></a>		y += dy;
<a name="54871"></a>		alert();
<a name="54872"></a>	}
<a name="54873"></a>	abstract void alert();
<a name="54874"></a>}
<br><a name="36437"></a>
abstract class ColoredPoint extends Point {
<a name="36438"></a>	int color;
<a name="36439"></a>}
<br><a name="54875"></a>
class SimplePoint extends Point {
<a name="54876"></a>	void alert() { }
<a name="54877"></a>}
</pre><a name="54878"></a>
a class <code>Point</code> is declared that must be declared <code>abstract</code>, because it contains a 
declaration of an <code>abstract</code> method named <code>alert</code>. The subclass of <code>Point</code> named<code> 
ColoredPoint</code> inherits the <code>abstract</code> method <code>alert</code>, so it must also be declared 
<code>abstract</code>. On the other hand, the subclass of <code>Point</code> named <code>SimplePoint</code> provides
an implementation of <code>alert</code>, so it need not be <code>abstract</code>.
<p><a name="14273"></a>
A compile-time error occurs if an attempt is made to create an instance of an <code>abstract</code> class using a class instance creation expression <a href="15.doc.html#41147">(&#167;15.8)</a>. An attempt to instantiate an <code>abstract</code> class using the <code>newInstance</code> method of class <code>Class</code> <a href="javalang.doc2.html#15088">(&#167;20.3.6)</a> will cause an <code>InstantiationException</code> <a href="11.doc.html#44285">(&#167;11.5.1)</a> to be thrown. Thus, continuing the example just shown, the statement:<p>
<pre><a name="54881"></a>	Point p = new Point();
</pre><a name="54883"></a>
would result in a compile-time error; the class <code>Point</code> cannot be instantiated 
because it is <code>abstract</code>. However, a <code>Point</code> variable could correctly be initialized 
with a reference to any subclass of <code>Point</code>, and the class <code>SimplePoint</code> is not 
<code>abstract</code>, so the statement:
<p><pre><a name="227781"></a>	Point p = new SimplePoint();
</pre><a name="227782"></a>
would be correct.
<p><a name="227783"></a>
A subclass of an <code>abstract</code> class that is not itself <code>abstract</code> may be instantiated, resulting in the execution of a constructor for the <code>abstract</code> class and, therefore, the execution of the field initializers for instance variables of that class. Thus, in the example just given, instantiation of a <code>SimplePoint</code> causes the default constructor and field initializers for <code>x</code> and <code>y</code> of <code>Point</code> to be executed.<p>
<a name="54900"></a>
It is a compile-time error to declare an <code>abstract</code> class type such that it is not possible to create a subclass that implements all of its <code>abstract</code> methods. This situation can occur if the class would have as members two <code>abstract</code> methods that have the same method signature <a href="8.doc.html#38649">(&#167;8.4.2)</a> but different return types. As an example, the declarations:<p>
<pre><a name="54908"></a>
interface Colorable { void setColor(int color); }
<a name="54909"></a>
abstract class Colored implements Colorable {
<a name="54910"></a>	abstract int setColor(int color);
<a name="54931"></a>}
</pre><a name="25369"></a>
result in a compile-time error: it would be impossible for any subclass of class 
<code>Colored</code> to provide an implementation of a method named <code>setColor</code>, taking one 
argument of type <code>int</code>, that can satisfy both <code>abstract</code> method specifications, 
because the one in interface <code>Colorable</code> requires the same method to return no 
value, while the one in class <code>Colored</code> requires the same method to return a value 
of type <code>int</code> <a href="8.doc.html#40420">(&#167;8.4)</a>.
<p><a name="36521"></a>
A class type should be declared <code>abstract</code> only if the intent is that subclasses can be created to complete the implementation. If the intent is simply to prevent instantiation of a class, the proper way to express this is to declare a constructor <a href="8.doc.html#16830">(&#167;8.6.8)</a> of no arguments, make it <code>private</code>, never invoke it, and declare no other constructors. A class of this form usually contains class methods and variables. The class <code>java.lang.Math</code> is an example of a class that cannot be instantiated; its declaration looks like this:<p>
<pre><a name="36522"></a>
public final class Math {
<br><a name="36523"></a>	private Math() { }							// never instantiate this class
<br><br><a name="36538"></a>	. . . declarations of class variables and methods . . .
<br><a name="36524"></a>}
</pre><a name="54727"></a>
<h4>8.1.2.2    final Classes</h4>
<a name="54729"></a>
A class can be declared <code>final</code> if its definition is complete and no subclasses are 
desired or required. A compile-time error occurs if the name of a <code>final</code> class 
appears in the <code>extends</code> clause <a href="8.doc.html#21723">(&#167;8.1.3)</a> of another <code>class</code> declaration; this implies 
that a <code>final</code> class cannot have any subclasses. A compile-time error occurs if a 
class is declared both <code>final</code> and <code>abstract</code>, because the implementation of such a 
class could never be completed <a href="8.doc.html#34944">(&#167;8.1.2.1)</a>.
<p><a name="36559"></a>
Because a <code>final</code> class never has any subclasses, the methods of a <code>final</code> class are never overridden <a href="8.doc.html#227927">(&#167;8.4.6.1)</a>.<p>
<a name="21723"></a>
<h3>8.1.3    Superclasses and Subclasses</h3>
<a name="29771"></a>
The optional <code>extends</code> clause in a class declaration specifies the <i>direct superclass</i> 
of the current class. A class is said to be a <i>direct subclass</i> of the class it extends. 
The direct superclass is the class from whose implementation the implementation 
of the current class is derived. The <code>extends</code> clause must not appear in the definition
of the class <code>java.lang.Object</code> <a href="javalang.doc1.html#46442">(&#167;20.1)</a>, because it is the primordial class 
and has no direct superclass. If the class declaration for any other class has no 
<code>extends</code> clause, then the class has the class <code>java.lang.Object</code> as its implicit 
direct superclass.
<p><ul><pre>
<i>Super:<br>
</i>	<code>extends </code><i>ClassType
</i></pre></ul><a name="229540"></a>
The following is repeated from <a href="4.doc.html#9317">&#167;4.3</a> to make the presentation here clearer:
<p><ul><pre>
<i>ClassType:<br>
</i>	<i>TypeName
</i></pre></ul><a name="29813"></a>
The <i>ClassType</i> must name an accessible <a href="6.doc.html#33916">(&#167;6.6)</a> class type, or a compile-time error occurs. All classes in the current package are accessible. Classes in other packages are accessible if the host system permits access to the package <a href="7.doc.html#37758">(&#167;7.2)</a> and the class is declared <code>public</code>. If the specified <i>ClassType </i>names a class that is <code>final</code> <a href="8.doc.html#54727">(&#167;8.1.2.2)</a>, then a compile-time error occurs; <code>final</code> classes are not allowed to have subclasses.<p>
<a name="34088"></a>
In the example:<p>
<pre><br><a name="34089"></a>class Point { int x, y; }
<br><br><a name="34090"></a>final class ColoredPoint extends Point { int color; }
<br><a name="34094"></a>class Colored3DPoint extends ColoredPoint { int z; } // error
</pre><a name="29322"></a>
the relationships are as follows:
<p><ul><a name="29323"></a>
<li>The class <code>Point</code> is a direct subclass of <code>java.lang.Object</code><i></i>.
<a name="29324"></a>
<li>The class <code>java.lang.Object</code> is the direct superclass of the class <code>Point</code><i></i>.
<a name="35258"></a>
<li>The class <code>ColoredPoint</code> is a direct subclass of class <code>Point</code><i></i>.
<a name="35261"></a>
<li>The class <code>Point</code> is the direct superclass of class <code>ColoredPoint</code>.
</ul><a name="35273"></a>
The declaration of class <code>Colored3dPoint</code> causes a compile-time error because it 
attempts to extend the <code>final</code> class <code>ColoredPoint</code>.
<p><a name="34079"></a>
The <i>subclass </i>relationship is the transitive closure of the direct subclass relationship. A class <i>A</i><i></i> is a subclass of class <i>C</i><i></i> if either of the following is true:<p>
<ul><a name="34080"></a>
<li><i>A</i> is the direct subclass of <i>C</i>.
<a name="34081"></a>
<li>There exists a class <i>B</i><i></i> such that <i>A</i><i></i> is a subclass of <i>B</i><i></i>, and <i>B</i><i></i> is a subclass of <i>C</i><i></i>, applying this definition recursively.
</ul><a name="34082"></a>
Class <i>C</i><i></i> is said to be a <i>superclass </i>of class <i>A</i><i></i> whenever <i>A</i><i> </i>is a subclass of <i>C</i><i></i>.
<p><a name="36594"></a>
In the example:<p>
<pre><br><a name="34023"></a>class Point { int x, y; }
<br><br><a name="34039"></a>class ColoredPoint extends Point { int color; }
<br><a name="34040"></a>final class Colored3dPoint extends ColoredPoint { int z; }
</pre><a name="35276"></a>
the relationships are as follows:
<p><ul><a name="36602"></a>
<li>The class <code>Point</code> is a superclass of class <code>ColoredPoint</code>.
<a name="36604"></a>
<li>The class <code>Point</code> is a superclass of class <code>Colored3dPoint</code><i></i>.
<a name="36611"></a>
<li>The class <code>ColoredPoint</code> is a subclass of class <code>Point</code>.
<a name="36613"></a>
<li>The class <code>ColoredPoint</code> is a superclass of class <code>Colored3dPoint</code><i></i>.
<a name="36619"></a>
<li>The class <code>Colored3dPoint</code> is a subclass of class <code>ColoredPoint</code>.
<a name="36621"></a>
<li>The class <code>Colored3dPoint</code> is a subclass of class <code>Point</code>.
</ul><a name="21739"></a>
A compile-time error occurs if a class is declared to be a subclass of itself. For 
example:
<p><pre><br><a name="34029"></a>class Point extends ColoredPoint { int x, y; }
<br><a name="45856"></a>class ColoredPoint extends Point { int color; }
</pre><a name="25374"></a>
causes a compile-time error. If circularly declared classes are detected at run time, 
as classes are loaded <a href="12.doc.html#44459">(&#167;12.2)</a>, then a <code>ClassCircularityError</code> is thrown.
<p><a name="34031"></a>
<h3>8.1.4    Superinterfaces</h3>
<a name="18953"></a>
The optional <code>implements</code> clause in a class declaration lists the names of interfaces
that are <i>direct superinterfaces</i> of the class being declared:
<p><ul><pre>
<i>Interfaces:<br>
</i>	<code>implements </code><i>InterfaceTypeList
</i>
<i>InterfaceTypeList:<br>
</i>	<i>InterfaceType<br>
</i>	<i>InterfaceTypeList</i><code> , </code><i>InterfaceType
</i></pre></ul><a name="229546"></a>
The following is repeated from <a href="4.doc.html#9317">&#167;4.3</a> to make the presentation here clearer:
<p><ul><pre>
<i>InterfaceType:<br>
</i>	<i>TypeName
</i></pre></ul><a name="34112"></a>
Each <i>InterfaceType</i> must name an accessible <a href="6.doc.html#33916">(&#167;6.6)</a> interface type, or a compile-
time error occurs. All interfaces in the current package are accessible. Interfaces 
in other packages are accessible if the host system permits access to the package 
<a href="7.doc.html#13194">(&#167;7.4.4)</a> and the interface is declared <code>public</code>.
<p><a name="36646"></a>
A compile-time error occurs if the same interface is mentioned two or more times in a single <code>implements</code> clause, even if the interface is named in different ways; for example, the code:<p>
<pre><a name="36651"></a>
class Redundant implements java.lang.Cloneable, Cloneable {
<a name="36652"></a>	int x;
<a name="36654"></a>}
</pre><a name="36655"></a>
results in a compile-time error because the names <code>java.lang.Cloneable</code> and 
<code>Cloneable</code> refer to the same interface.
<p><a name="31147"></a>
An interface type <i>I</i><i></i> is a <i>superinterface</i> of class type <i>C</i><i></i> if any of the following is true:<p>
<ul><a name="34118"></a>
<li><i>I</i><i></i> is a direct superinterface of <i>C</i>.
<a name="29862"></a>
<li><i>C</i><i></i> has some direct superinterface <i>J</i><i></i> for which <i>I</i><i></i> is a superinterface<i></i>, using the definition of "superinterface of an interface" given in <a href="9.doc.html#78598">&#167;9.1.3</a>.
<a name="34121"></a>
<li><i>I</i><i></i> is a superinterface of the direct superclass of <i>C</i><i></i>, using this definition recursively.
</ul><a name="29918"></a>
A class is said to <i>implement</i> all its superinterfaces.
<p><a name="229105"></a>
In the example:<p>
<pre><a name="29875"></a>
public interface Colorable {
<a name="29876"></a>	void setColor(int color);
<a name="29877"></a>	int getColor();
<a name="29878"></a>}
<br><a name="29879"></a>
public interface Paintable extends Colorable {
<a name="29880"></a>	int MATTE = 0, GLOSSY = 1;
<a name="29881"></a>	void setFinish(int finish);
<a name="29882"></a>	int getFinish();
<a name="29883"></a>}
<br><br><a name="29884"></a>class Point { int x, y; }
<br><a name="29885"></a>
class ColoredPoint extends Point implements Colorable {
<a name="29886"></a>	int color;
<a name="29888"></a>	public void setColor(int color) { this.color = color; }
<a name="29889"></a>	public int getColor() { return color; }
<a name="29890"></a>}
<br><a name="29891"></a>
class PaintedPoint extends ColoredPoint implements Paintable <br>
{
<a name="29892"></a>	int finish;
<a name="29893"></a>	public void setFinish(int finish) {
<a name="230320"></a>		this.finish = finish;
<a name="230321"></a>	}
<a name="29894"></a>	public int getFinish() { return finish; }
<a name="29895"></a>}
</pre><a name="29896"></a>
the relationships are as follows:
<p><ul><a name="29897"></a>
<li>The interface <code>Paintable</code> is a superinterface of class <code>PaintedPoint</code>.
<a name="29898"></a>
<li>The interface <code>Colorable</code> is a superinterface of class <code>ColoredPoint</code> and of class <code>PaintedPoint</code>.
<a name="29899"></a>
<li>The interface <code>Paintable</code> is a subinterface of the interface <code>Colorable</code>, and <code>Colorable</code> is a superinterface of <code>Paintable</code>, <code>a</code>s defined in <a href="9.doc.html#78598">&#167;9.1.3</a>.
</ul><a name="29912"></a>
A class can have a superinterface in more than one way. In this example, the class 
<code>PaintedPoint</code> has <code>Colorable</code> as a superinterface both because it is a superinterface
of <code>ColoredPoint</code> and because it is a superinterface of <code>Paintable</code>.
<p><a name="29870"></a>
Unless the class being declared is <code>abstract</code>, the declarations of the methods defined in each direct superinterface must be implemented either by a declaration in this class or by an existing method declaration inherited from the direct superclass, because a class that is not <code>abstract</code> is not permitted to have <code>abstract</code> methods <a href="8.doc.html#34944">(&#167;8.1.2.1)</a>.<p>
<a name="230327"></a>
Thus, the example:<p>
<pre><a name="16122"></a>
interface Colorable {
<a name="16123"></a>	void setColor(int color);
<a name="16124"></a>	int getColor();
<a name="16125"></a>}
<br><br><a name="16126"></a>class Point { int x, y; };
<br><a name="16127"></a>
class ColoredPoint extends Point implements Colorable {
<a name="16128"></a>	int color;
<a name="16129"></a>}
</pre><a name="36705"></a>
causes a compile-time error, because <code>ColoredPoint</code> is not an <code>abstract</code> class but 
it fails to provide an implementation of methods <code>setColor</code> and <code>getColor</code> of the 
interface <code>Colorable</code>.
<p><a name="228059"></a>
It is permitted for a single method declaration in a class to implement methods of more than one superinterface. For example, in the code:<p>
<pre><br><a name="228063"></a>interface Fish { int getNumberOfScales(); }
<br><br><a name="228065"></a>interface Piano { int getNumberOfScales(); }
<br></pre><pre><a name="228061"></a>
class Tuna implements Fish, Piano {
<a name="228070"></a>	// You can tune a piano, but can you tuna fish?
<a name="228069"></a>	int getNumberOfScales() { return 91; }
<a name="228068"></a>}
</pre><a name="228071"></a>
the method <code>getNumberOfScales</code> in class <code>Tuna</code> has a name, signature, and return 
type that matches the method declared in interface <code>Fish</code> and also matches the 
method declared in interface <code>Piano</code>; it is considered to implement both.
<p><a name="228080"></a>
On the other hand, in a situation such as this:<p>
<pre><br><a name="228083"></a>interface Fish { int getNumberOfScales(); }
<br><br><a name="228084"></a>interface StringBass { double getNumberOfScales(); }
<br></pre><pre><a name="228085"></a>
class Bass implements Fish, StringBass {
<a name="228086"></a>	// This declaration cannot be correct, no matter what type is used.
<a name="228087"></a>	public ??? getNumberOfScales() { return 91; }
<a name="228088"></a>}
</pre><a name="228081"></a>
it is impossible to declare a method named <code>getNumberOfScales</code> with the same 
signature and return type as those of both the methods declared in interface <code>Fish</code> 
and in interface <code>StringBass</code>, because a class can have only one method with a 
given signature <a href="8.doc.html#40420">(&#167;8.4)</a>. Therefore, it is impossible for a single class to implement 
both interface <code>Fish</code> and interface <code>StringBass</code> <a href="8.doc.html#228745">(&#167;8.4.6)</a>.
<p><a name="18988"></a>
<h3>8.1.5    Class Body and Member Declarations</h3>
<a name="77979"></a>
A <i>class body</i> may contain declarations of members of the class, that is, fields 
<a href="8.doc.html#40898">(&#167;8.3)</a> and methods <a href="8.doc.html#40420">(&#167;8.4)</a>. A class body may also contain static initializers <a href="8.doc.html#39245">(&#167;8.5)</a> 
and declarations of constructors <a href="8.doc.html#41652">(&#167;8.6)</a> for the class.
<p><ul><pre>
<i>ClassBody:<br>
	</i><code>{ </code><i>ClassBodyDeclarations</i><sub><i>opt</i></sub><code> }
</code>
<i>ClassBodyDeclarations:<br>
</i>	<i>ClassBodyDeclaration<br>
</i>	<i>ClassBodyDeclarations</i><code> </code><i>ClassBodyDeclaration
</i>
<i>ClassBodyDeclaration:<br>
	ClassMemberDeclaration<br>
	StaticInitializer<br>
	ConstructorDeclaration
</i>
<i>ClassMemberDeclaration:<br>
	FieldDeclaration<br>
</i>	<i>MethodDeclaration
</i></pre></ul><a name="14175"></a>
The scope of the name of a member declared in or inherited by a class type is the 
entire body of the class type declaration.
<p><a name="21831"></a>
<h2>8.2    Class Members</h2>
<a name="40942"></a>
The members of a class type are all of the following:
<p><ul><a name="40946"></a>
<li>Members inherited from its direct superclass <a href="8.doc.html#21723">(&#167;8.1.3)</a>, except in class <code>Object</code>, which has no direct superclass
<a name="45862"></a>
<li>Members inherited from any direct superinterfaces <a href="8.doc.html#34031">(&#167;8.1.4)</a>
<a name="45866"></a>
<li>Members declared in the body of the class <a href="8.doc.html#18988">(&#167;8.1.5)</a>
</ul><a name="30394"></a>
Members of a class that are declared <code>private</code> are not inherited by subclasses of that class. Only members of a class that are declared <code>protected</code> or <code>public</code> are inherited by subclasses declared in a package other than the one in which the class is declared.<p>
<a name="230007"></a>
Constructors and static initializers are not members and therefore are not inherited.<p>
<a name="36731"></a>
The example:<p>
<pre><a name="14608"></a>
class Point {
<a name="14609"></a>	int x, y;
<a name="36739"></a>	private Point() { reset(); }
<a name="14610"></a>	Point(int x, int y) { this.x = x; this.y = y; }
<a name="16317"></a>	private void reset() { this.x = 0; this.y = 0; }
<a name="14611"></a>}
<br><a name="14612"></a>
class ColoredPoint extends Point {
<a name="36760"></a>	int color;
<a name="36761"></a>	void clear() { reset(); }														// error
<a name="36762"></a>}
<br><a name="14615"></a>
class Test {
<a name="14616"></a>	public static void main(String[] args) {
<a name="14617"></a>		ColoredPoint c = new ColoredPoint(0, 0);													// error
<a name="16316"></a>		c.reset();													// error
<a name="14618"></a>	}
<a name="14619"></a>}
</pre><a name="14620"></a>
causes four compile-time errors:
<p><ul><a name="16328"></a>
<li>An error occurs because <code>ColoredPoint</code> has no constructor declared with two integer parameters, as requested by the use in <code>main</code>. This illustrates the fact that <code>ColoredPoint</code> does not inherit the constructors of its superclass <code>Point</code>.
<a name="16329"></a>
<li>Another error occurs because <code>ColoredPoint</code> declares no constructors, and therefore a default constructor for it is automatically created <a href="8.doc.html#16823">(&#167;8.6.7)</a>, and this default constructor is equivalent to:
<a name="14624"></a>	ColoredPoint() { super(); }
</ul><ul><a name="14625"></a>
<br><br>which invokes the constructor, with no arguments, for the direct superclass of the class <code>ColoredPoint</code>. The error is that the constructor for <code>Point</code> that takes no arguments is <code>private</code>, and therefore is not accessible outside the class <code>Point</code>, even through a superclass constructor invocation <a href="8.doc.html#78435">(&#167;8.6.5)</a>.
</ul><ul><a name="16327"></a>
<li>Two more errors occur because the method <code>reset</code> of class <code>Point</code> is <code>private</code>, and therefore is not inherited by class <code>ColoredPoint</code>. The method invocations in method <code>clear</code> of class <code>ColoredPoint</code> and in method <code>main</code> of class <code>Test</code> are therefore not correct.
</ul><a name="30229"></a>
<h3>8.2.1    Examples of Inheritance</h3>
<a name="36776"></a>
This section illustrates inheritance of class members through several examples.
<p><a name="40830"></a>
<h4>8.2.1.1    Example: Inheritance with Default Access</h4>
<a name="40831"></a>
Consider the example where the <code>points</code> package declares two compilation units:
<p><pre><br><a name="40832"></a>package points;
<br></pre><pre><a name="40833"></a>
public class Point {
<a name="40834"></a>	int x, y;<br>
	public void move(int dx, int dy) { x += dx; y += dy; }
<a name="40835"></a>}
</pre><a name="40836"></a>
and:
<p><pre><br><a name="40837"></a>package points;
<br></pre><pre><a name="40838"></a>
public class Point3d extends Point {
<a name="40839"></a>	int z;
<a name="40840"></a>	public void move(int dx, int dy, int dz) {
<a name="40841"></a>		x += dx; y += dy; z += dz;
<a name="40842"></a>	}
<a name="40843"></a>}
</pre><a name="40844"></a>
and a third compilation unit, in another package, is:
<p><pre><br><a name="40845"></a>import points.Point3d;
<br></pre><pre><a name="40846"></a>
class Point4d extends Point3d {
<a name="40847"></a>	int w;
<a name="40848"></a>	public void move(int dx, int dy, int dz, int dw) {
<a name="40849"></a>		x += dx; y += dy; z += dz; w += dw; // compile-time errors
<a name="40850"></a>	}
<a name="40851"></a>}
</pre><a name="40852"></a>
Here both classes in the <code>points</code> package compile. The class <code>Point3d</code> inherits the 
fields <code>x</code> and <code>y</code> of class <code>Point</code>, because it is in the same package as <code>Point</code>. The 
class <code>Point4d</code>, which is in a different package, does not inherit the fields <code>x</code> and <code>y</code> 
of class <code>Point</code> or the field <code>z</code> of class <code>Point3d</code>, and so fails to compile.
<p><a name="40853"></a>
A better way to write the third compilation unit would be:<p>
<pre><br><a name="40854"></a>import points.Point3d;
<br></pre><pre><a name="40855"></a>
class Point4d extends Point3d {
<a name="40856"></a>	int w;
<a name="40857"></a>	public void move(int dx, int dy, int dz, int dw) {
<a name="40858"></a>		super.move(dx, dy, dz); w += dw;
<a name="40859"></a>	}
<a name="40860"></a>}
</pre><a name="40861"></a>
using the <code>move</code> method of the superclass <code>Point3d</code> to process <code>dx</code>, <code>dy</code>, and <code>dz</code>. If 
<code>Point4d</code> is written in this way it will compile without errors.
<p><a name="40862"></a>
<h4>8.2.1.2    Inheritance with public and protected</h4>
<a name="40863"></a>
Given the class <code>Point</code>:
<p><pre><br><a name="40864"></a>package points;
<br></pre><pre><a name="40865"></a>
public class Point {
<br><a name="40866"></a>	public int x, y;
<br><br><a name="40867"></a>	protected int useCount = 0;
<br><br><a name="40868"></a>	static protected int totalUseCount = 0;
<br><a name="36785"></a>
	public void move(int dx, int dy) {
<a name="40869"></a>		x += dx; y += dy; useCount++; totalUseCount++;
<a name="40870"></a>	}
<br><a name="40871"></a>}
</pre><a name="40872"></a>
the <code>public</code> and <code>protected</code> fields <code>x</code>, <code>y</code>, <code>useCount</code> and <code>totalUseCount</code> are inherited
in all subclasses of <code>Point</code>. Therefore, this test program, in another package, 
can be compiled successfully:
<p><pre><a name="40873"></a>
class Test extends points.Point {
<a name="40874"></a>	public void moveBack(int dx, int dy) {
<a name="40875"></a>		x -= dx; y -= dy; useCount++; totalUseCount++;
<a name="40876"></a>	}
<a name="40877"></a>}
</pre><a name="40879"></a>
<h4>8.2.1.3    Inheritance with private</h4>
<a name="40880"></a>
In the example:
<p><pre><a name="40881"></a>
class Point {
<br><a name="40882"></a>	int x, y;
<br><a name="40883"></a>
	void move(int dx, int dy) {
<a name="40884"></a>		x += dx; y += dy; totalMoves++;
<a name="40885"></a>	}
<br><br><a name="40886"></a>	private static int totalMoves;
<br><br><a name="40887"></a>	void printMoves() { System.out.println(totalMoves); }
<br><a name="40888"></a>}
<br><a name="40889"></a>
class Point3d extends Point {
<br><a name="40890"></a>	int z;
<br><a name="40891"></a>
	void move(int dx, int dy, int dz) {
<a name="40892"></a>		super.move(dx, dy); z += dz; totalMoves++;
<a name="40893"></a>	}
<br><a name="40894"></a>}
</pre><a name="40822"></a>
the class variable totalMoves can be used only within the class <code>Point</code>; it is not 
inherited by the subclass <code>Point3d</code>. A compile-time error occurs at the point where 
method <code>move</code> of class <code>Point3d</code> tries to increment totalMoves.
<p><a name="23530"></a>
<h4>8.2.1.4    Accessing Members of Inaccessible Classes</h4>
<a name="23515"></a>
Even though a class might not be declared <code>public</code>, instances of the class might be 
available at run time to code outside the package in which it is declared if it has a 
<code>public</code> superclass or superinterface. An instance of the class can be assigned to a 
variable of such a <code>public</code> type. An invocation of a <code>public</code> method of the object 
referred to by such a variable may invoke a method of the class if it implements or 
overrides a method of the <code>public</code> superclass or superinterface. (In this situation, 
the method is necessarily declared <code>public</code>, even though it is declared in a class 
that is not <code>public</code>.)
<p><a name="23519"></a>
Consider the compilation unit:<p>
<pre><br><a name="36842"></a>package points;
<br></pre><pre><a name="36843"></a>
public class Point {
<a name="36844"></a>	public int x, y;
<a name="36847"></a>	public void move(int dx, int dy) {
<a name="36848"></a>		x += dx; y += dy;
<a name="36849"></a>	}
<a name="36850"></a>}
</pre><a name="36865"></a>
and another compilation unit of another package:
<p><pre><br><a name="23520"></a>package morePoints;
<br></pre><pre><a name="23521"></a>
class Point3d extends points.Point {
<a name="23522"></a>	public int z;
<a name="36870"></a>	public void move(int dx, int dy, int dz) {
<a name="36871"></a>		super.move(dx, dy); z += dz;
<a name="36872"></a>	}
<a name="23523"></a>}
<br><a name="23524"></a>
public class OnePoint {
<a name="23525"></a>	static points.Point getOne() { return new Point3d(); }
<a name="23526"></a>}
</pre><a name="23527"></a>
An invocation <code>morePoints.OnePoint.getOne()</code> in yet a third package would 
return a <code>Point3d</code> that can be used as a <code>Point</code>, even though the type <code>Point3d</code> is 
not available outside the package <code>morePoints</code>. The method <code>move</code> could then be 
invoked for that object, which is permissible because method <code>move</code> of <code>Point3d</code> is 
<code>public</code> (as it must be, for any method that overrides a <code>public</code> method must itself 
be <code>public</code>, precisely so that situations such as this will work out correctly). The 
fields <code>x</code> and <code>y</code> of that object could also be accessed from such a third package.
<p><a name="36884"></a>
While the field <code>z</code> of class <code>Point3d</code> is <code>public</code>, it is not possible to access this field from code outside the package <code>morePoints</code>, given only a reference to an instance of class <code>Point3d</code> in a variable <code>p</code> of type <code>Point</code>. This is because the expression <code>p.z</code> is not correct, as <code>p</code> has type <code>Point</code> and class <code>Point</code> has no field named <code>z</code>; also, the expression <code>((Point3d)p).z</code> is not correct, because the class type <code>Point3d</code> cannot be referred to outside package <code>morePoints</code>. The declaration of the field <code>z</code> as <code>public</code> is not useless, however. If there were to be, in package <code>morePoints</code>, a <code>public</code> subclass <code>Point4d</code> of the class <code>Point3d</code>:<p>
<pre><br><a name="36889"></a>package morePoints;
<br></pre><pre><a name="36890"></a>
public class Point4d extends Point3d {
<a name="36891"></a>	public int w;
<a name="36892"></a>	public void move(int dx, int dy, int dz, int dw) {
<a name="36893"></a>		super.move(dx, dy, dz); w += dw;
<a name="36894"></a>	}
<a name="36896"></a>}
<br></pre><a name="36887"></a>
then class <code>Point4d</code> would inherit the field <code>z</code>, which, being <code>public</code>, could then be 
accessed by code in packages other than <code>morePoints</code>, through variables and 
expressions of the <code>public</code> type <code>Point4d</code>.
<p><a name="40898"></a>
<h2>8.3    Field Declarations</h2>
<a name="40823"></a>
The variables of a class type are introduced by <i>field declarations</i>:
<p><ul><pre>
<i>FieldDeclaration:<br>
	FieldModifiers</i><sub><i>opt</i></sub><code> </code><i>Type</i><code> </code><i>VariableDeclarators</i><code> ;
</code>
<i>VariableDeclarators:<br>
</i>	<i>VariableDeclarator<br>
</i>	<i>VariableDeclarators</i><code> , </code><i>VariableDeclarator
</i>
<i>VariableDeclarator:<br>
</i>	<i>VariableDeclaratorId<br>
</i>	<i>VariableDeclaratorId</i><code> = </code><i>VariableInitializer
</i>
<i>VariableDeclaratorId:<br>
</i>	<i>Identifier<br>
</i>	<i>VariableDeclaratorId</i><code> [ ]
</code>
<i>VariableInitializer:<br>
</i>	<i>Expression<br>
</i>	<i>ArrayInitializer
</i></pre></ul><a name="78087"></a>
The <i>FieldModifiers</i> are described in <a href="8.doc.html#78091">&#167;8.3.1</a>. The <i>Identifier</i> in a <i>FieldDeclarator</i> 
may be used in a name to refer to the field. The name of a field has as its scope 
<a href="6.doc.html#33623">(&#167;6.3)</a> the entire body of the class declaration in which it is declared. More than 
one field may be declared in a single field declaration by using more than one 
declarator; the <i>FieldModifiers</i> and <i>Type</i> apply to all the declarators in the declaration.
Variable declarations involving array types are discussed in <a href="10.doc.html#25891">&#167;10.2</a>.
<p><a name="29989"></a>
It is a compile-time error for the body of a class declaration to contain declarations of two fields with the same name. Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures <a href="6.doc.html#20569">(&#167;6.5)</a>.<p>
<a name="36999"></a>
If the class declares a field with a certain name, then the declaration of that field is said to <i>hide</i> <a href="6.doc.html#34133">(&#167;6.3.1)</a> any and all accessible declarations of fields with the same name in the superclasses and superinterfaces of the class.<p>
<a name="38152"></a>
If a field declaration hides the declaration of another field, the two fields need not have the same type.<p>
<a name="38148"></a>
A class inherits from its direct superclass and direct superinterfaces all the fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.<p>
<a name="37087"></a>
It is possible for a class to inherit more than one field with the same name <a href="8.doc.html#40491">(&#167;8.3.3.3)</a>. Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the class to refer to any such field by its simple name will result in a compile-time error, because such a reference is ambiguous.<p>
<a name="37038"></a>
There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.<p>
<a name="37037"></a>
A hidden field can be accessed by using a qualified name (if it is <code>static</code>) or by using a field access expression <a href="15.doc.html#41267">(&#167;15.10)</a> that contains the keyword <code>super</code> or a cast to a superclass type. See <a href="15.doc.html#20860">&#167;15.10.2</a> for discussion and an example.<p>
<a name="78091"></a>
<h3>8.3.1    Field Modifiers</h3>
<ul><pre>
<i>FieldModifiers:<br>
	FieldModifier<br>
	FieldModifiers</i><code> </code><i>FieldModifier
</i>
<i>FieldModifier: one of<br>
	</i><code>public&#32;protected&#32;private<br>
	final&#32;static&#32;transient&#32;volatile
</code></pre></ul><a name="35964"></a>
The access modifiers <code>public</code>, <code>protected</code>, and <code>private</code> are discussed in <a href="6.doc.html#33916">&#167;6.6</a>. A 
compile-time error occurs if the same modifier appears more than once in a field 
declaration, or if a field declaration has more than one of the access modifiers 
<code>public</code>, <code>protected</code>, and <code>private</code>. If two or more (distinct) field modifiers 
appear in a field declaration, it is customary, though not required, that they appear 
in the order consistent with that shown above in the production for <i>FieldModifier</i>.
<p><a name="37544"></a>
<h4>8.3.1.1    static Fields</h4>
<a name="230789"></a>
If a field is declared <code>static</code>, there exists exactly one incarnation of the field, no 
matter how many instances (possibly zero) of the class may eventually be created. 
A <code>static</code> field, sometimes called a <i>class variable</i>, is incarnated when the class is 
initialized <a href="12.doc.html#44557">(&#167;12.4)</a>.
<p><a name="230793"></a>
A field that is not declared <code>static</code> (sometimes called a non-<code>static</code> field) is called an <i>instance variable</i>. Whenever a new instance of a class is created, a new variable associated with that instance is created for every instance variable declared in that class or any of its superclasses.<p>
<a name="38985"></a>
The example program:<p>
<pre><a name="37567"></a>
class Point {
<a name="37568"></a>	int x, y, useCount;
<a name="37569"></a>	Point(int x, int y) { this.x = x; this.y = y; }
<a name="37572"></a>	final static Point origin = new Point(0, 0);
<a name="37573"></a>}
<br><a name="37574"></a>
class Test {
<a name="37575"></a>	public static void main(String[] args) {
<a name="37576"></a>		Point p = new Point(1,1);
<a name="37577"></a>		Point q = new Point(2,2);
<a name="37578"></a>		p.x = 3; p.y = 3; p.useCount++; p.origin.useCount++;
<a name="37579"></a>		System.out.println("(" + q.x + "," + q.y + ")");
<a name="37615"></a>		System.out.println(q.useCount);
<a name="37581"></a>		System.out.println(q.origin == Point.origin);
<a name="37662"></a>		System.out.println(q.origin.useCount);
<a name="37582"></a>	}
<a name="37583"></a>}
</pre><a name="37584"></a>
prints:
<p><pre><a name="37585"></a>
(2,2)
<a name="37618"></a>0
<a name="37587"></a>true
<a name="37667"></a>1
</pre><a name="37588"></a>
showing that changing the fields <code>x</code>, <code>y</code>, and <code>useCount</code> of <code>p</code> does not affect the fields 
of <code>q</code>, because these fields are instance variables in distinct objects. In this example, 
the class variable <code>origin</code> of the class <code>Point</code> is referenced both using the class 
name as a qualifier, in <code>Point.origin</code>, and using variables of the class type in 
field access expressions <a href="15.doc.html#41267">(&#167;15.10)</a>, as in <code>p.origin</code> and <code>q.origin</code>. These two ways 
of accessing the <code>origin</code> class variable access the same object, evidenced by the 
fact that the value of the reference equality expression <a href="15.doc.html#236163">(&#167;15.20.3)</a>:
<p><pre><a name="227823"></a><code>q.origin==Point.origin
</code></pre><a name="227825"></a>
is <code>true</code>. Further evidence is that the incrementation:
<p><pre><a name="37670"></a>p.origin.useCount++;
</pre><a name="37671"></a>
causes the value of q.origin.useCount to be <code>1</code>; this is so because <code>p.origin</code> and 
<code>q.origin</code> refer to the same variable.
<p><a name="35962"></a>
<h4>8.3.1.2    final Fields</h4>
<a name="14727"></a>
A field can be declared <code>final</code>, in which case its declarator must include a variable 
initializer or a compile-time error occurs. Both class and instance variables 
(<code>static</code> and non-<code>static</code> fields) may be declared <code>final</code>.
<p><a name="37504"></a>
Any attempt to assign to a <code>final</code> field results in a compile-time error. Therefore, once a <code>final</code> field has been initialized, it always contains the same value. If a <code>final</code> field holds a reference to an object, then the state of the object may be changed by operations on the object, but the field will always refer to the same object. This applies also to arrays, because arrays are objects; if a <code>final</code> field holds a reference to an array, then the components of the array may be changed by operations on the array, but the field will always refer to the same array.<p>
<a name="14728"></a>
Declaring a field <code>final</code> can serve as useful documentation that its value will not change, can help to avoid programming errors, and can make it easier for a compiler to generate efficient code.<p>
<a name="37005"></a>
In the example:<p>
<pre><a name="37006"></a>
class Point {
<a name="37053"></a>	int x, y;
<a name="37066"></a>	int useCount;
<a name="37049"></a>	Point(int x, int y) { this.x = x; this.y = y; }
<a name="37058"></a>	final static Point origin = new Point(0, 0);
<a name="37056"></a>}
</pre><a name="37059"></a>
the class <code>Point</code> declares a <code>final</code> class variable <code>origin</code>. The <code>origin</code> variable 
holds a reference to an object that is an instance of class <code>Point</code> whose coordinates 
are (0, 0). The value of the variable <code>Point.origin</code> can never change, so it always 
refers to the same <code>Point</code> object, the one created by its initializer. However, an 
operation on this <code>Point</code> object might change its state-for example, modifying its 
<code>useCount</code> or even, misleadingly, its <code>x</code> or <code>y</code> coordinate.
<p><a name="78119"></a>
<h4>8.3.1.3    transient Fields</h4>
<a name="37020"></a>
Variables may be marked <code>transient</code> to indicate that they are not part of the persistent
state of an object. If an instance of the class <code>Point</code>:
<p><pre><a name="14770"></a>
class Point {
<a name="14771"></a>	int x, y;
<a name="14772"></a>	transient float rho, theta;
<a name="14773"></a>}
</pre><a name="14775"></a>
were saved to persistent storage by a system service, then only the fields <code>x</code> and <code>y</code> 
would be saved. This specification does not yet specify details of such services; 
we intend to provide them in a future version of this specification.
<p><a name="36930"></a>
<h4>8.3.1.4    volatile Fields</h4>
<a name="37715"></a>
As described in <a href="17.doc.html#26250">&#167;17</a>, the Java language allows threads that access shared variables 
to keep private working copies of the variables; this allows a more efficient implementation
of multiple threads. These working copies need be reconciled with the 
master copies in the shared main memory only at prescribed synchronization 
points, namely when objects are locked or unlocked. As a rule, to ensure that 
shared variables are consistently and reliably updated, a thread should ensure that 
it has exclusive use of such variables by obtaining a lock that, conventionally, 
enforces mutual exclusion for those shared variables.
<p><a name="37727"></a>
Java provides a second mechanism that is more convenient for some purposes: a field may be declared <code>volatile</code>, in which case a thread must reconcile its working copy of the field with the master copy every time it accesses the variable. Moreover, operations on the master copies of one or more volatile variables on behalf of a thread are performed by the main memory in exactly the order that the thread requested.<p>
<a name="14790"></a>
If, in the following example, one thread repeatedly calls the method <code>one</code> (but no more than <code>Integer.MAX_VALUE</code> <a href="javalang.doc6.html#2391">(&#167;20.7.2)</a> times in all), and another thread repeatedly calls the method <code>two</code>:<p>
<pre><a name="14792"></a>
class Test {
<br><a name="14793"></a>	static int i = 0, j = 0;
<br><a name="14794"></a>
	static void one() { i++; j++; }
<a name="14796"></a>
	static void two() {
<a name="14797"></a>		System.out.println("i=" + i + " j=" + j);
<a name="14801"></a>	}
<br><a name="14802"></a>}
</pre><a name="14803"></a>
then method <code>two</code> could occasionally print a value for <code>j</code> that is greater than the 
value of <code>i</code>, because the example includes no synchronization and, under the rules 
explained in <a href="17.doc.html#26250">&#167;17</a>, the shared values of <code>i</code> and <code>j</code> might be updated out of order.
<p><a name="37738"></a>
One way to prevent this out-or-order behavior would be to declare methods <code>one</code> and <code>two</code> to be <code>synchronized</code> <a href="8.doc.html#55408">(&#167;8.4.3.5)</a>:<p>
<pre><a name="37768"></a>
class Test {
<br><a name="37769"></a>	static int i = 0, j = 0;
<br><a name="37770"></a>
	static synchronized void one() { i++; j++; }
<a name="37771"></a>
	static synchronized void two() {
<a name="37772"></a>		System.out.println("i=" + i + " j=" + j);
<a name="37773"></a>	}
<br><a name="37774"></a>}
</pre><a name="37777"></a>
This prevents method <code>one</code> and method <code>two</code> from being executed concurrently, and 
furthermore guarantees that the shared values of <code>i</code> and <code>j</code> are both updated before 
method <code>one</code> returns. Therefore method <code>two</code> never observes a value for <code>j</code> greater 
than that for <code>i</code>; indeed, it always observes the same value for <code>i</code> and <code>j</code>.
<p><a name="37789"></a>
Another approach would be to declare <code>i</code> and <code>j</code> to be <code>volatile</code>:<p>
<pre><a name="37793"></a>
class Test {
<br><a name="37794"></a>	static volatile int i = 0, j = 0;
<br><a name="37795"></a>
	static void one() { i++; j++; }
<a name="37796"></a>
	static void two() {
<a name="37797"></a>		System.out.println("i=" + i + " j=" + j);
<a name="37798"></a>	}
<br><a name="37799"></a>}
</pre><a name="37800"></a>
This allows method <code>one</code> and method <code>two</code> to be executed concurrently, but guarantees
that accesses to the shared values for <code>i</code> and <code>j</code> occur exactly as many times, 
and in exactly the same order, as they appear to occur during execution of the program
text by each thread. Therefore, method <code>two</code> never observes a value for <code>j</code> 
greater than that for <code>i</code>, because each update to <code>i</code> must be reflected in the shared 
value for <code>i</code> before the update to <code>j</code> occurs. It is possible, however, that any given 
invocation of method <code>two</code> might observe a value for <code>j</code> that is much greater than the 
value observed for <code>i</code>, because method <code>one</code> might be executed many times between 
the moment when method <code>two</code> fetches the value of <code>i</code> and the moment when 
method <code>two</code> fetches the value of <code>j</code>.
<p><a name="14791"></a>
See <a href="17.doc.html#26250">&#167;17</a> for more discussion and examples.<p>
<a name="24509"></a>
A compile-time error occurs if a <code>final</code> variable is also declared <code>volatile</code>.<p>
<a name="24510"></a>
<h3>8.3.2    Initialization of Fields</h3>
<a name="41082"></a>
If a field declarator contains a <i>variable initializer</i>, then it has the semantics of an 
assignment <a href="15.doc.html#5281">(&#167;15.25)</a> to the declared variable, and:
<p><ul><a name="37635"></a>
<li>If the declarator is for a class variable (that is, a <code>static</code> field), then the variable initializer is evaluated and the assignment performed exactly once, when the class is initialized <a href="12.doc.html#44557">(&#167;12.4)</a>.
<a name="37639"></a>
<li>If the declarator is for an instance variable (that is, a field that is not <code>static</code>), then the variable initializer is evaluated and the assignment performed each time an instance of the class is created <a href="12.doc.html#44670">(&#167;12.5)</a>. 
</ul><a name="38002"></a>
The example:<p>
<pre><a name="30354"></a>
class Point {
<a name="30355"></a>	int x = 1, y = 5;
<a name="30356"></a>}
<br><a name="30357"></a>class Test {
<a name="30358"></a>	public static void main(String[] args) {
<a name="30359"></a>		Point p = new Point();
<a name="30360"></a>		System.out.println(p.x + ", " + p.y);
<a name="30361"></a>	}
<a name="30362"></a>}
</pre><a name="30363"></a>
produces the output:
<p><pre><a name="30377"></a>1, 5
</pre><a name="30378"></a>
because the assignments to <code>x</code> and <code>y</code> occur whenever a new <code>Point</code> is created.
<p><a name="30370"></a>
Variable initializers are also used in local variable declaration statements <a href="14.doc.html#5920">(&#167;14.3)</a>, where the initializer is evaluated and the assignment performed each time the local variable declaration statement is executed.<p>
<a name="38006"></a>
It is a compile-time error if the evaluation of a variable initializer for a field of a class (or interface) can complete abruptly with a checked exception <a href="11.doc.html#44121">(&#167;11.2)</a>.<p>
<a name="38010"></a>
<h4>8.3.2.1    Initializers for Class Variables</h4>
<a name="229741"></a>
A compile-time error occurs if an initialization expression for a class variable contains
a use by a simple name of that class variable or of another class variable 
whose declaration occurs to its right (that is, textually later) in the same class. 
Thus:
<p><pre><a name="229742"></a>
class Test {
<a name="229743"></a>	static float f = j;							// compile-time error: forward reference
<a name="229744"></a>	static int j = 1;
<a name="229745"></a>	static int k = k+1;							// compile-time error: forward reference
<a name="229746"></a>}
</pre><a name="229747"></a>
causes two compile-time errors, because <code>j</code> is referred to in the initialization of <code>f</code> 
before <code>j</code> is declared and because the initialization of <code>k</code> refers to <code>k</code> itself.
<p><a name="37971"></a>
If a reference by simple name to any instance variable occurs in an initialization expression for a class variable, then a compile-time error occurs.<p>
<a name="37934"></a>
If the keyword <code>this</code> <a href="15.doc.html#31980">(&#167;15.7.2)</a> or the keyword <code>super</code> (<a href="15.doc.html#20860">&#167;15.10.2</a>, <a href="15.doc.html#20448">&#167;15.11</a>) occurs in an initialization expression for a class variable, then a compile-time error occurs.<p>
<a name="229548"></a>
(One subtlety here is that, at run time, <code>static</code> variables that are <code>final</code> and that are initialized with compile-time constant values are initialized first. This also applies to such fields in interfaces <a href="9.doc.html#40720">(&#167;9.3.1)</a>. These variables are "constants" that will never be observed to have their default initial values <a href="4.doc.html#10931">(&#167;4.5.4)</a>, even by devious programs. See <a href="12.doc.html#44630">&#167;12.4.2</a> and <a href="13.doc.html#45139">&#167;13.4.8</a> for more discussion.)<p>
<a name="38013"></a>
<h4>8.3.2.2    Initializers for Instance Variables</h4>
<a name="30374"></a>
A compile-time error occurs if an initialization expression for an instance variable 
contains a use by a simple name of that instance variable or of another instance 
variable whose declaration occurs to its right (that is, textually later) in the same 
class. Thus:
<p><pre><a name="27881"></a>
class Test {
<a name="27882"></a>	float f = j;
<a name="27883"></a>	int j = 1;
<a name="37876"></a>	int k = k+1;
<a name="27884"></a>}
</pre><a name="27885"></a>
causes two compile-time errors, because <code>j</code> is referred to in the initialization of <code>f</code> 
before <code>j</code> is declared and because the initialization of <code>k</code> refers to <code>k</code> itself.
<p><a name="37982"></a>
Initialization expressions for instance variables may use the simple name of any <code>static</code> variable declared in or inherited by the class, even one whose declaration occurs textually later. Thus the example:<p>
<pre><a name="37983"></a>
class Test {
<a name="37984"></a>	float f = j;
<a name="37985"></a>	static int j = 1;
<a name="37987"></a>}
</pre><a name="37988"></a>
compiles without error; it initializes <code>j</code> to <code>1</code> when class <code>Test</code> is initialized, and initializes
<code>f</code> to the current value of <code>j</code> every time an instance of class <code>Test</code> is created.
<p><a name="40409"></a>
Initialization expressions for instance variables are permitted to refer to the current object <code>this</code> <a href="15.doc.html#31980">(&#167;15.7.2)</a> and to use the keyword <code>super</code> (<a href="15.doc.html#20860">&#167;15.10.2</a>, <a href="15.doc.html#20448">&#167;15.11</a>).<p>
<a name="40425"></a>
<h3>8.3.3    Examples of Field Declarations</h3>
<a name="40426"></a>
The following examples illustrate some (possibly subtle) points about field declarations.

<p><a name="40428"></a>
<h4>8.3.3.1    Example: Hiding of Class Variables</h4>
<a name="40429"></a>
The example:
<p><pre><a name="40430"></a>
class Point {
<a name="40431"></a>	static int x = 2;
<a name="40432"></a>}
<br><a name="40433"></a>
class Test extends Point {
<a name="40434"></a>	static double x = 4.7;
<a name="40435"></a>	public static void main(String[] args) {<br>
		new Test().printX();
<a name="229781"></a>	}
<a name="229782"></a>	void printX() {
<a name="40436"></a>		System.out.println(x + " " + super.x);
<a name="40437"></a>	}
<a name="40438"></a>}
</pre><a name="40439"></a>
produces the output:
<p><pre><a name="40440"></a>4.7 2
</pre><a name="40441"></a>
because the declaration of <code>x</code> in class <code>Test</code> hides the definition of <code>x</code> in class <code>Point</code>, 
so class <code>Test</code> does not inherit the field <code>x</code> from its superclass <code>Point</code>. Within the 
declaration of class <code>Test</code>, the simple name <code>x</code> refers to the field declared within 
class <code>Test</code>. Code in class <code>Test</code> may refer to the field <code>x</code> of class <code>Point</code> as <code>super.x</code> 
(or, because <code>x</code> is <code>static</code>, as <code>Point.x</code>). If the declaration of <code>Test.x</code> is deleted:
<p><pre><a name="40442"></a>
class Point {
<a name="40443"></a>	static int x = 2;
<a name="40444"></a>}
<br><a name="40445"></a>
class Test extends Point {
<a name="229789"></a>	public static void main(String[] args) {
<a name="229790"></a>		new Test().printX();
<a name="229791"></a>	}
<a name="229786"></a>	void printX() {
<a name="40447"></a>		System.out.println(x + " " + super.x);
<a name="40448"></a>	}
<a name="40449"></a>}
</pre><a name="40450"></a>
then the field <code>x</code> of class <code>Point</code> is no longer hidden within class <code>Test</code>; instead, the 
simple name <code>x</code> now refers to the field <code>Point.x</code>. Code in class <code>Test</code> may still refer 
to that same field as <code>super.x</code>. Therefore, the output from this variant program is:
<p><pre><a name="40451"></a>2 2
</pre><a name="229119"></a>
<h4>8.3.3.2    Example: Hiding of Instance Variables</h4>
<a name="40453"></a>
This example is similar to that in the previous section, but uses instance variables 
rather than static variables. The code:
<p><pre><a name="40454"></a>
class Point {
<a name="40455"></a>	int x = 2;
<a name="40456"></a>}
<br><a name="40457"></a>
class Test extends Point {
<a name="40458"></a>	double x = 4.7;
<a name="40459"></a>	void printBoth() {
<a name="40460"></a>		System.out.println(x + " " + super.x);
<a name="40461"></a>	}
<a name="40462"></a>	public static void main(String[] args) {
<a name="40463"></a>		Test sample = new Test();
<a name="40464"></a>		sample.printBoth();
<a name="40465"></a>		System.out.println(sample.x + " " + <br>
												((Point)sample).x);
<a name="40466"></a>	}
<a name="40467"></a>}
</pre><a name="40468"></a>
produces the output:
<p><pre><a name="40469"></a>
4.7 2
<a name="40470"></a>4.7 2
</pre><a name="40471"></a>
because the declaration of <code>x</code> in class <code>Test</code> hides the definition of <code>x</code> in class <code>Point</code>, 
so class <code>Test</code> does not inherit the field <code>x</code> from its superclass <code>Point</code>. It must be 
noted, however, that while the field <code>x</code> of class <code>Point</code> is not <i>inherited</i> by class 
<code>Test</code>, it is nevertheless <i>implemented</i> by instances of class <code>Test</code>. In other words, 
every instance of class <code>Test</code> contains two fields, one of type <code>int</code> and one of type 
<code>float</code>. Both fields bear the name <code>x</code>, but within the declaration of class <code>Test</code>, the 
simple name <code>x</code> always refers to the field declared within class <code>Test</code>. Code in 
instance methods of class <code>Test</code> may refer to the instance variable <code>x</code> of class <code>Point</code> 
as <code>super.x</code>.
<p><a name="40472"></a>
Code that uses a field access expression to access field <code>x</code> will access the field named <code>x</code> in the class indicated by the type of reference expression. Thus, the expression <code>sample.x</code> accesses a <code>float</code> value, the instance variable declared in class <code>Test</code>, because the type of the variable sample is <code>Test</code>, but the expression <code>((Point)sample).x</code> accesses an <code>int</code> value, the instance variable declared in class <code>Point</code>, because of the cast to type <code>Point</code>.<p>
<a name="40473"></a>
If the declaration of <code>x</code> is deleted from class <code>Test</code>, as in the program:<p>
<pre><a name="40474"></a>
class Point {
<a name="40475"></a>	static int x = 2;
<a name="40476"></a>}
<br><a name="40477"></a>
class Test extends Point {
<a name="40478"></a>	void printBoth() {
<a name="40479"></a>		System.out.println(x + " " + super.x);
<a name="40480"></a>	}
<a name="40481"></a>	public static void main(String[] args) {
<a name="40482"></a>		Test sample = new Test();
<a name="40483"></a>		sample.printBoth();
<a name="40484"></a>		System.out.println(sample.x + " " +<br>
												((Point)sample).x);
<a name="40485"></a>	}
<a name="40486"></a>}
</pre><a name="40487"></a>
then the field <code>x</code> of class <code>Point</code> is no longer hidden within class <code>Test</code>. Within 
instance methods in the declaration of class <code>Test</code>, the simple name <code>x</code> now refers to 
the field declared within class <code>Point</code>. Code in class <code>Test</code> may still refer to that 
same field as <code>super.x</code>. The expression <code>sample.x</code> still refers to the field <code>x</code> within 
type <code>Test</code>, but that field is now an inherited field, and so refers to the field <code>x</code> 
declared in class <code>Point</code>. The output from this variant program is:
<p><pre><a name="40488"></a>
2 2
<a name="40489"></a>2 2
</pre><a name="40491"></a>
<h4>8.3.3.3    Example: Multiply Inherited Fields</h4>
<a name="40492"></a>
A class may inherit two or more fields with the same name, either from two interfaces
or from its superclass and an interface. A compile-time error occurs on any 
attempt to refer to any ambiguously inherited field by its simple name. A qualified 
name or a field access expression that contains the keyword <code>super</code> <a href="15.doc.html#20860">(&#167;15.10.2)</a> may 
be used to access such fields unambiguously. In the example:
<p><pre><br><a name="40496"></a>interface Frob { float v = 2.0f; }
<br><br><a name="40497"></a>class SuperTest { int v = 3; }
<br></pre><pre><a name="40498"></a>
class Test extends SuperTest implements Frob {
<a name="40499"></a>	public static void main(String[] args) {
<a name="40500"></a>		new Test().printV();
<a name="40501"></a>	}
<a name="40502"></a>	void printV() { System.out.println(v); }
<a name="40503"></a>}
</pre><a name="40504"></a>
the class <code>Test</code> inherits two fields named <code>v</code>, one from its superclass <code>SuperTest</code> and 
one from its superinterface <code>Frob</code>. This in itself is permitted, but a compile-time 
error occurs because of the use of the simple name <code>v</code> in method <code>printV</code>: it cannot 
be determined which <code>v</code> is intended.
<p><a name="41191"></a>
The following variation uses the field access expression <code>super.v</code> to refer to the field named <code>v</code> declared in class <code>SuperTest</code> and uses the qualified name <code>Frob.v</code> to refer to the field named <code>v</code> declared in interface <code>Frob</code>:<p>
<pre><br><a name="40505"></a>interface Frob { float v = 2.0f; }
<br><br><a name="40506"></a>class SuperTest { int v = 3; }
<br></pre><pre><a name="40507"></a>
class Test extends SuperTest implements Frob {
<a name="40508"></a>	public static void main(String[] args) {
<a name="40509"></a>		new Test().printV();
<a name="40510"></a>	}
<a name="40511"></a>	void printV() {
<a name="40512"></a>		System.out.println((super.v + Frob.v)/2);
<a name="40513"></a>	}
<a name="40514"></a>}
</pre><a name="40515"></a>
It compiles and prints:
<p><pre><a name="40516"></a>2.5
</pre><a name="40518"></a>
Even if two distinct inherited fields have the same type, the same value, and are both <code>final</code>, any reference to either field by simple name is considered ambiguous and results in a compile-time error. In the example:<p>
<pre><br><a name="40519"></a>interface Color { int RED=0, GREEN=1, BLUE=2; }
<br><br><a name="40520"></a>interface TrafficLight { int RED=0, YELLOW=1, GREEN=2; }
<br></pre><pre><a name="40521"></a>
class Test implements Color, TrafficLight {
<a name="40522"></a>	public static void main(String[] args) {
<a name="40523"></a>		System.out.println(GREEN);										// compile-time error
<a name="40524"></a>		System.out.println(RED);										// compile-time error
<a name="40525"></a>	}
<a name="40526"></a>}
</pre><a name="40527"></a>
it is not astonishing that the reference to <code>GREEN</code> should be considered ambiguous, 
because class <code>Test</code> inherits two different declarations for <code>GREEN</code> with different 
values. The point of this example is that the reference to <code>RED</code> is also considered 
ambiguous, because two distinct declarations are inherited. The fact that the two 
fields named <code>RED</code> happen to have the same type and the same unchanging value 
does not affect this judgment.
<p><a name="40528"></a>
<h4>8.3.3.4    Example: Re-inheritance of Fields</h4>
<a name="40529"></a>
If the same field declaration is inherited from an interface by multiple paths, the 
field is considered to be inherited only once. It may be referred to by its simple 
name without ambiguity. For example, in the code:
<p><pre><a name="40530"></a>
public interface Colorable {
<a name="40531"></a>	int RED = 0xff0000, GREEN = 0x00ff00, BLUE = 0x0000ff;
<a name="40532"></a>}
<br><a name="40533"></a>
public interface Paintable extends Colorable {
<a name="40534"></a>	int MATTE = 0, GLOSSY = 1;
<a name="40535"></a>}
<br><br><a name="40536"></a>class Point { int x, y; }
<br><a name="40537"></a>
class ColoredPoint extends Point implements Colorable {
<a name="40538"></a>	. . .
<a name="40539"></a>}
<br><a name="40540"></a>
class PaintedPoint extends ColoredPoint implements Paintable 
{
<a name="40541"></a>	. . .  &#32; &#32; &#32;<code>RED</code> &#32; &#32; &#32; . . .
<a name="40542"></a>}
</pre><a name="40423"></a>
the fields <code>RED</code>, <code>GREEN</code>, and <code>BLUE</code> are inherited by the class <code>PaintedPoint</code> both 
through its direct superclass <code>ColoredPoint</code> and through its direct superinterface 
<code>Paintable</code>. The simple names <code>RED</code>, <code>GREEN</code>, and <code>BLUE</code> may nevertheless be used 
without ambiguity within the class <code>PaintedPoint</code> to refer to the fields declared in 
interface <code>Colorable</code>.
<p><a name="40420"></a>
<h2>8.4    Method Declarations</h2>
<a name="40422"></a>
A <i>method</i> declares executable code that can be invoked, passing a fixed number of 
values as arguments.
<p><ul><pre>
<i>MethodDeclaration:<br>
</i>	<i>MethodHeader</i><code> </code><i>MethodBody
</i>
<i>MethodHeader:<br>
	MethodModifiers</i><sub><i>opt</i></sub><code> </code><i>ResultType</i><code> </code><i>MethodDeclarator</i><code> </code><i>Throws</i><sub><i>opt
</i></sub>
<i>ResultType:<br>
	Type<br>
	</i><code>void
</code>
<i>MethodDeclarator:<br>
</i>	<i>Identifer</i><code> ( </code><i>FormalParameterList</i><sub><i>opt</i></sub><code> )
</code></pre></ul><a name="37508"></a>
The <i>MethodModifiers</i> are described in <a href="8.doc.html#78188">&#167;8.4.3</a>, the <i>Throws</i> clause in <a href="8.doc.html#78323">&#167;8.4.4</a>, and the 
<i>MethodBody</i> in <a href="8.doc.html#37316">&#167;8.4.5</a>. A method declaration either specifies the type of value that 
the method returns or uses the keyword <code>void</code> to indicate that the method does not 
return a value.
<p><a name="30386"></a>
The <i>Identifier</i> in a <i>MethodDeclarator</i> may be used in a name to refer to the method. A class can declare a method with the same name as the class or a field of the class.<p>
<a name="38703"></a>
For compatibility with older versions of Java, a declaration form for a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the parameter list. This is supported by the obsolescent production:<p>
<ul><pre>
<i>MethodDeclarator:<br>
</i>	<i>MethodDeclarator</i><code> [ ]
</code></pre></ul><a name="38705"></a>
but should not be used in new Java code.
<p><a name="38056"></a>
It is a compile-time error for the body of a class to have as members two methods with the same signature <a href="8.doc.html#38649">(&#167;8.4.2)</a> (name, number of parameters, and types of any parameters). Methods and fields may have the same name, since they are used in different contexts and are disambiguated by the different lookup procedures <a href="6.doc.html#20569">(&#167;6.5)</a>.<p>
<a name="38698"></a>
<h3>8.4.1    Formal Parameters</h3>
<a name="37472"></a>
The <i>formal parameters</i> of a method, if any, are specified by a list of comma-separated
parameter specifiers. Each parameter specifier consists of a type and an identifier
(optionally followed by brackets) that specifies the name of the parameter:
<p><ul><pre>
<i>FormalParameterList:<br>
</i>	<i>FormalParameter<br>
</i>	<i>FormalParameterList</i><code> , </code><i>FormalParameter
</i>
<i>FormalParameter:<br>
</i>	<i>Type</i><code> </code><i>VariableDeclaratorId
</i></pre></ul><a name="14850"></a>
The following is repeated from <a href="8.doc.html#40898">&#167;8.3</a> to make the presentation here clearer:
<p><ul><pre>
<i>VariableDeclaratorId:<br>
</i>	<i>Identifier<br>
</i>	<i>VariableDeclaratorId</i><code> [ ]
</code></pre></ul><a name="55499"></a>
If a method has no parameters, only an empty pair of parentheses appears in the method's declaration.<p>
<a name="55500"></a>
If two formal parameters are declared to have the same name (that is, their declarations mention the same <i>Identifier</i>), then a compile-time error occurs.<p>
<a name="37477"></a>
When the method is invoked <a href="15.doc.html#20448">(&#167;15.11)</a>, the values of the actual argument expressions initialize newly created parameter variables, each of the declared <i>Type,</i> before execution of the body of the method. The <i>Identifier</i> that appears<i> </i>in the <i>DeclaratorId</i> may be used as a simple name in the body of the method to refer to the formal parameter.<p>
<a name="38643"></a>
The scope of formal parameter names is the entire body of the method. These parameter names may not be redeclared as local variables or exception parameters within the method; that is, hiding the name of a parameter is not permitted.<p>
<a name="38647"></a>
Formal parameters are referred to only using simple names, never by using qualified names <a href="6.doc.html#33916">(&#167;6.6)</a>.<p>
<a name="38649"></a>
<h3>8.4.2    Method Signature</h3>
<a name="37479"></a>
The <i>signature</i> of a method consists of the name of the method and the number and 
types of formal parameters to the method. A class may not declare two methods 
with the same signature, or a compile-time error occurs. The example:
<p><pre><a name="41347"></a>
class Point implements Move {
<a name="41348"></a>	int x, y;
<a name="41349"></a>	abstract void move(int dx, int dy);
<a name="41350"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<a name="41351"></a>}
</pre><a name="41352"></a>
causes a compile-time error because it declares two <code>move</code> methods with the same 
signature. This is an error even though one of the declarations is <code>abstract</code>.
<p><a name="78188"></a>
<h3>8.4.3    Method Modifiers</h3>
<ul><pre>
<i>MethodModifiers:<br>
	MethodModifier<br>
	MethodModifiers</i><code> </code><i>MethodModifier
</i>
<i>MethodModifier: one of<br>
	</i><code>public&#32;protected&#32;private<br>
	abstract&#32;static&#32;final&#32;synchronized&#32;native
</code></pre></ul><a name="35992"></a>
The access modifiers <code>public</code>, <code>protected</code>, and <code>private</code> are discussed in <a href="6.doc.html#33916">&#167;6.6</a>. 
A &#32;compile-time error occurs if the same modifier appears more than once in a 
method declaration, or if a method declaration has more than one of the access 
modifiers <code>public</code>, <code>protected</code>, and <code>private</code>. A compile-time error occurs if a 
method declaration that contains the keyword <code>abstract</code> also contains any one of 
the keywords <code>private</code>, <code>static</code>, <code>final</code>, <code>native</code>, or <code>synchronized</code>.
<p><a name="38745"></a>
If two or more method modifiers appear in a method declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for <i>MethodModifier</i>.<p>
<a name="34484"></a>
<h4>8.4.3.1    abstract Methods</h4>
<a name="38742"></a>
An <code>abstract</code> method declaration introduces the method as a member, providing 
its signature (name and number and type of parameters), return type, and <code>throws</code> 
clause (if any), but does not provide an implementation. The declaration of an 
<code>abstract</code> method <i>m</i> must appear within an <code>abstract</code> class (call it <i>A</i><i></i>); otherwise a 
compile-time error results. Every subclass of <i>A</i><i> </i>that is not <code>abstract</code> must provide 
an implementation for <i>m</i>, or a compile-time error occurs. More precisely, for every 
subclass <i>C</i> of the <code>abstract</code> class <i>A</i><i></i>, if <i>C</i><i></i> is not <code>abstract</code>, then there must be some 
class <i>B</i><i></i> such that all of the following are true:
<p><ul><a name="78209"></a>
<li><i>B</i> is a superclass of <i>C</i><i> </i>or is <i>C</i><i></i> itself.
<a name="78210"></a>
<li><i>B</i> is a subclass of <i>A</i><i></i>.
<a name="78212"></a>
<li><i>B</i> provides a declaration of the method <i>m</i> that is not <code>abstract</code>, and this declaration is inherited by <i>C</i>, thereby providing an implementation of method <i>m</i> that is visible to <i>C</i><i></i>.
</ul><a name="227750"></a>
If there is no such class <i>B</i>, then<i></i> a compile-time error occurs.
<p><a name="230064"></a>
It is a compile-time error for a <code>private</code> method to be declared <code>abstract</code>. It would be impossible for a subclass to implement a <code>private</code> <code>abstract</code> method, because <code>private</code> methods are not visible to subclasses; therefore such a method could never be used.<p>
<a name="230065"></a>
It is a compile-time error for a <code>static</code> method to be declared <code>abstract</code>.<p>
<a name="230073"></a>
It is a compile-time error for a <code>final</code> method to be declared <code>abstract</code>.<p>
<a name="36710"></a>
An <code>abstract</code> class can override an <code>abstract</code> method by providing another <code>abstract</code> method declaration. This can provide a place to put a documentation comment <a href="18.doc.html#25978">(&#167;18)</a>, or to declare that the set of checked exceptions <a href="11.doc.html#44121">(&#167;11.2)</a> that can be thrown by that method, when it is implemented by its subclasses, is to be more limited. For example, consider this code:<p>
<pre><a name="36711"></a>
class BufferEmpty extends Exception {
<a name="29450"></a>	BufferEmpty() { super(); }
<a name="29451"></a>	BufferEmpty(String s) { super(s); }
<a name="29452"></a>}
<br><a name="25657"></a>
class BufferError extends Exception {
<a name="29453"></a>	BufferError() { super(); }
<a name="29454"></a>	BufferError(String s) { super(s); }
<a name="29455"></a>}
<br><a name="25660"></a>
public interface Buffer {
<a name="36714"></a>	char get() throws BufferEmpty, BufferError;
<a name="36715"></a>}
<br><a name="36716"></a>
public abstract class InfiniteBuffer implements Buffer {
<a name="36717"></a>	abstract char get() throws BufferError;
<a name="36718"></a>}
</pre><a name="11245"></a>
The overriding declaration of method <code>get</code> in class <code>InfiniteBuffer</code> states that 
method <code>get</code> in any subclass of <code>InfiniteBuffer</code> never throws a <code>BufferEmpty</code> 
exception, putatively because it generates the data in the buffer, and thus can never 
run out of data.
<p><a name="14765"></a>
An instance method that is not <code>abstract</code> can be overridden by an <code>abstract</code> method. For example, we can declare an <code>abstract</code> class <code>Point</code> that requires its subclasses to implement <code>toString</code> if they are to be complete, instantiable classes:<p>
<pre><a name="14908"></a>
abstract class Point {
<a name="14909"></a>	int x, y;
<a name="14910"></a>	public abstract String toString();
<a name="14911"></a>}
</pre><a name="14912"></a>
This <code>abstract</code> declaration of <code>toString</code> overrides the non-<code>abstract</code> <code>toString</code> 
method of class <code>Object</code> <a href="javalang.doc1.html#1152">(&#167;20.1.2)</a>. (Class <code>Object</code> is the implicit direct superclass 
of class <code>Point</code>.) Adding the code:
<p><pre><a name="38907"></a>
class ColoredPoint extends Point {
<a name="38908"></a>	int color;
<a name="38909"></a>	public String toString() {
<a name="38919"></a>		return super.toString() + ": color " + color; // error
<a name="38920"></a>	}
<a name="38910"></a>}
</pre><a name="38923"></a>
results in a compile-time error because the invocation <code>super.toString()</code> refers 
to method <code>toString</code> in class <code>Point</code>, which is <code>abstract</code> and therefore cannot be 
invoked. Method <code>toString</code> of class <code>Object</code> can be made available to class 
<code>ColoredPoint</code> &#32;only if class <code>Point</code> explicitly makes it available through some 
other method, as in:
<p><pre><a name="38928"></a>
abstract class Point {
<a name="38929"></a>	int x, y;
<a name="38930"></a>	public abstract String toString();
<a name="38945"></a>	protected String objString() { return super.toString(); }
<a name="38931"></a>}
<a name="38933"></a>
class ColoredPoint extends Point {
<a name="38934"></a>	int color;
<a name="38935"></a>	public String toString() {
<a name="38936"></a>		return objString() + ": color " + color;														// correct
<a name="229125"></a>	}
<a name="229126"></a>}
</pre><a name="229128"></a>
<h4>8.4.3.2    static Methods</h4>
<a name="39431"></a>
A method that is declared <code>static</code> is called a <i>class method</i>. A class method is 
always invoked without reference to a particular object. An attempt to reference 
the current object using the keyword <code>this</code> or the keyword <code>super</code> in the body of a 
class method results in a compile time error. It is a compile-time error for a 
<code>static</code> method to be declared <code>abstract</code>.
<p><a name="39033"></a>
A method that is not declared <code>static</code> is called an <i>instance method,</i> and sometimes called a non-<code>static</code> method). An instance method is always invoked with respect to an object, which becomes the current object to which the keywords <code>this</code> and <code>super</code> refer during execution of the method body.<p>
<a name="11246"></a>
<h4>8.4.3.3    final Methods</h4>
<a name="30456"></a>
A method can be declared <code>final</code> to prevent subclasses from overriding or hiding 
it. It is a compile-time error to attempt to override or hide a <code>final</code> method.
<p><a name="38958"></a>
A <code>private</code> method and all methods declared in a <code>final</code> class <a href="8.doc.html#54727">(&#167;8.1.2.2)</a> are implicitly <code>final</code>, because it is impossible to override them. It is permitted but not required for the declarations of such methods to redundantly include the <code>final</code> keyword. <p>
<a name="38950"></a>
It is a compile-time error for a <code>final</code> method to be declared <code>abstract</code>.<p>
<a name="14844"></a>
At run-time, a machine-code generator or optimizer can easily and safely "inline" the body of a <code>final</code> method, replacing an invocation of the method with the code in its body, as in the example:<p>
<pre><a name="36655"></a>
final class Point {
<a name="36656"></a>	int x, y;
<a name="36657"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<a name="36658"></a>}
<br><a name="36659"></a>
class Test {
<a name="36660"></a>	public static void main(String[] args) {
<a name="36661"></a>		Point[] p = new Point[100];
<a name="36662"></a>		for (int i = 0; i &lt; p.length; i++) {
<a name="25669"></a>			p[i] = new Point();
<a name="36663"></a>			p[i].move(i, p.length-1-i);
<a name="25670"></a>		}
<a name="36664"></a>	}
<a name="36665"></a>}
</pre><a name="36666"></a>
Here, inlining the method <code>move</code> of class <code>Point</code> in method <code>main</code> would transform 
the <code>for</code> loop to the form:
<p><pre><a name="36667"></a>
		for (int i = 0; i &lt; p.length; i++) {
<a name="25671"></a>			p[i] = new Point();
<a name="36668"></a>			Point pi = p[i];
<a name="36669"></a>			pi.x += i;
<a name="36670"></a>			pi.y += p.length-1-i;
<a name="36671"></a>		}
</pre><a name="31122"></a>
The loop might then be subject to further optimizations.
<p><a name="31123"></a>
Such inlining cannot be done at compile time unless it can be guaranteed that <code>Test</code> and <code>Point</code> will always be recompiled together, so that whenever <code>Point</code>-and specifically its <code>move</code> method-changes, the code for <code>Test.main</code> will also be updated.<p>
<a name="31125"></a>
<h4>8.4.3.4    native Methods</h4>
<a name="30468"></a>
A method that is <code>native</code> is implemented in platform-dependent code, typically 
written in another programming language such as C, C++, FORTRAN, or assembly 
language. The body of a <code>native</code> method is given as a semicolon only, indicating 
that the implementation is omitted, instead of a block.
<p><a name="38981"></a>
A compile-time error occurs if a <code>native</code> method is declared <code>abstract</code>.<p>
<a name="38035"></a>
For example, the class <code>RandomAccessFile</code> of the standard package <code>java.io</code> might declare the following <code>native</code> methods:<p>
<pre><br><a name="14929"></a>package java.io;
<br></pre><pre><a name="229136"></a>
public class RandomAccessFile<br>
	implements DataOutput, DataInput
<a name="14948"></a>{	. . .
<a name="14949"></a>	public native void open(String name, boolean writeable)
<a name="14930"></a>		throws IOException;
<a name="14931"></a>	public native int readBytes(byte[] b, int off, int len)
<a name="14932"></a>		throws IOException;
<a name="14933"></a>	public native void writeBytes(byte[] b, int off, int len)
<a name="14934"></a>		throws IOException;
<a name="14935"></a>	public native long getFilePointer() throws IOException;
<a name="14944"></a>	public native void seek(long pos) throws IOException;
<a name="14940"></a>	public native long length() throws IOException;
<a name="27670"></a>	public native void close() throws IOException;
<a name="14950"></a>}
</pre><a name="55408"></a>
<h4>8.4.3.5    synchronized Methods</h4>
<a name="30531"></a>
A <code>synchronized</code> method acquires a lock <a href="17.doc.html#28287">(&#167;17.1)</a> before it executes. For a class 
(<code>static)</code> method, the lock associated with the <code>Class</code> object <a href="javalang.doc2.html#14342">(&#167;20.3)</a> for the 
method's class is used. For an instance method, the lock associated with <code>this</code> (the 
object for which the method was invoked) is used. These are the same locks that 
can be used by the <code>synchronized</code> statement <a href="14.doc.html#79287">(&#167;14.17)</a>; thus, the code:
<p><pre><a name="39079"></a>
class Test {
<a name="39082"></a>	int count;
<a name="39085"></a>	synchronized void bump() { count++; }
<a name="39095"></a>	static int classCount;
<a name="39087"></a>	static synchronized void classBump() {
<a name="39107"></a>		classCount++;
<a name="39108"></a>	}
<a name="39080"></a>}
</pre><a name="39096"></a>
has exactly the same effect as:
<p><pre><a name="39099"></a>
class BumpTest {
<a name="39100"></a>	int count;
<a name="39101"></a>	void bump() {
<a name="227909"></a>		synchronized (this) {
<a name="227908"></a>			count++;
<a name="227910"></a>		}
<a name="227911"></a>	}
<a name="39102"></a>	static int classCount;
<a name="39103"></a>	static void classBump() {
<a name="229768"></a>		try {
<a name="39119"></a>			synchronized (Class.forName("BumpTest")) {
<a name="39114"></a>				classCount++;
<a name="229774"></a>			}
<a name="229769"></a>		} catch (ClassNotFoundException e) {
<a name="229770"></a>				...
<a name="229771"></a>		}
<a name="39115"></a>	}
<a name="39104"></a>}
</pre><a name="39078"></a>
The more elaborate example:
<p><pre><a name="30532"></a>
public class Box {
<br><a name="30533"></a>	private Object boxContents;
<br><a name="30534"></a>
	public synchronized Object get() {
<a name="30535"></a>		Object contents = boxContents;
<a name="30536"></a>		boxContents = null;
<a name="30537"></a>		return contents;
<a name="30538"></a>	}
<br><a name="30539"></a>
	public synchronized boolean put(Object contents) {
<a name="30540"></a>		if (boxContents != null)
<a name="30541"></a>			return false;
<a name="30542"></a>		boxContents = contents;
<a name="30543"></a>		return true;
<a name="30544"></a>	}
<br><a name="30545"></a>}
</pre><a name="30546"></a>
defines a class which is designed for concurrent use. Each instance of the class 
<code>Box</code> has an instance variable <code>contents</code> that can hold a reference to any object. 
You can put an object in a <code>Box</code> by invoking <code>put</code>, which returns <code>false</code> if the box is 
already full. You can get something out of a <code>Box</code> by invoking <code>get</code>, which returns a 
null reference if the <code>box</code> is empty.
<p><a name="39151"></a>
If <code>put</code> and <code>get</code> were not <code>synchronized</code>, and two threads were executing methods for the same instance of <code>Box</code> at the same time, then the code could misbehave. It might, for example, lose track of an object because two invocations to <code>put</code> occurred at the same time.<p>
<a name="39159"></a>
See <a href="17.doc.html#26250">&#167;17</a> for more discussion of threads and locks.<p>
<a name="78323"></a>
<h3>8.4.4    Method Throws</h3>
<a name="41401"></a>
A <i>throws clause</i> is used to declare any checked exceptions <a href="11.doc.html#44121">(&#167;11.2)</a> that can result 
from the execution of a method or constructor:
<p><ul><pre>
<i>Throws:<br>
</i><code>	throws </code><i>ClassTypeList
</i>
<i>ClassTypeList:<br>
</i>	<i>ClassType<br>
</i>	<i>ClassTypeList</i><code> , </code><i>ClassType
</i></pre></ul><a name="39173"></a>
A compile-time error occurs if any <i>ClassType</i> mentioned in a <code>throws</code> clause is not 
the class <code>Throwable</code> <a href="javalang.doc20.html#46198">(&#167;20.22)</a> or a subclass of <code>Throwable</code>. It is permitted but not 
required to mention other (unchecked) exceptions in a <code>throws</code> clause.
<p><a name="39177"></a>
For each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless that exception type or a superclass of that exception type is mentioned in a <code>throws</code> clause in the declaration of the method or constructor.<p>
<a name="24551"></a>
The requirement to declare checked exceptions allows the compiler to ensure that code for handling such error conditions has been included. Methods or constructors that fail to handle exceptional conditions thrown as checked exceptions will normally result in a compile-time error because of the lack of a proper exception type in a <code>throws</code> clause. Java thus encourages a programming style where rare and otherwise truly exceptional conditions are documented in this way.<p>
<a name="55271"></a>
The predefined exceptions that are not checked in this way are those for which declaring every possible occurrence would be unimaginably inconvenient:<p>
<ul><a name="41434"></a>
<li>Exceptions that are represented by the subclasses of class <code>Error</code>, for example <code>OutOfMemoryError</code>, are thrown due to a failure in or of the virtual machine. Many of these are the result of linkage failures and can occur at unpredictable points in the execution of a Java program. Sophisticated programs may yet wish to catch and attempt to recover from some of these conditions.
<a name="41435"></a>
<li>The exceptions that are represented by the subclasses of the class <code>RuntimeException</code>, &#32;for example <code>NullPointerException</code>, result from runtime &#32;integrity checks and are thrown either directly from the Java program or in library routines. It is beyond the scope of the Java language, and perhaps beyond the state of the art, to include sufficient information in the program to reduce to a manageable number the places where these can be proven not to occur.
</ul><a name="230101"></a>
A method that overrides or hides another method <a href="8.doc.html#228745">(&#167;8.4.6)</a>, including methods that implement <code>abstract</code> methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.<p>
<a name="230102"></a>
More precisely, suppose that <i>B</i><i></i> is a class or interface, and <i>A</i><i></i> is a superclass or superinterface of <i>B</i>, and a method declaration <i>n</i> in <i>B</i> overrides or hides a method declaration <i>m</i> in <i>A</i><i></i>. If <i>n</i><i></i> has a <code>throws</code> clause that mentions any checked exception types, then <i>m</i> must have a <code>throws</code> clause, and for every checked exception type listed in the <code>throws</code> clause of <i>n</i>, that same exception class or one of its superclasses must occur in the <code>throws</code> clause of <i>m</i>; otherwise, a compile-time error occurs.<p>
<a name="24563"></a>
See <a href="11.doc.html#44043">&#167;11</a> for more information about exceptions and a large example.<p>
<a name="37316"></a>
<h3>8.4.5    Method Body</h3>
<a name="32175"></a>
A <i>method body</i> is either a block of code that implements the method or simply a 
semicolon, indicating the lack of an implementation. The body of a method must 
be a semicolon if and only if the method is either <code>abstract</code> <a href="8.doc.html#34484">(&#167;8.4.3.1)</a> or <code>native</code> 
<a href="8.doc.html#31125">(&#167;8.4.3.4)</a>.
<p><ul><pre>
<i>MethodBody:<br>
	Block</i> <br>
	<code>;
</code></pre></ul><a name="38770"></a>
A compile-time error occurs if a method declaration is either <code>abstract</code> or 
<code>native</code> and has a block for its body. A compile-time error occurs if a method declaration
is neither <code>abstract</code> nor <code>native</code> and has a semicolon for its body.
<p><a name="39311"></a>
If an implementation is to be provided for a method but the implementation requires no executable code, the method body should be written as a block that contains no statements: "<code>{ }</code>".<p>
<a name="228178"></a>
If a method is declared <code>void</code>, then its body must not contain any <code>return</code> statement <a href="14.doc.html#6767">(&#167;14.15)</a> that has an <i>Expression</i>.<p>
<a name="244552"></a>
If a method is declared to have a return type, then every <code>return</code> statement <a href="14.doc.html#6767">(&#167;14.15)</a> in its body must have an <i>Expression</i>. A compile-time error occurs if the body of the method can complete normally <a href="14.doc.html#5894">(&#167;14.1)</a>. In other words, a method with a return type must return only by using a return statement that provides a value return; it is not allowed to "drop off the end of its body."<p>
<a name="228370"></a>
Note that it is possible for a method to have a declared return type and yet contain no return statements. Here is one example:<p>
<pre><a name="228742"></a>class DizzyDean {<br>
	int pitch() { throw new RuntimeException("90 mph?!"); }<br>
}
</pre><a name="228745"></a>
<h3>8.4.6    Inheritance, Overriding, and Hiding</h3>
<a name="227926"></a>
A class <i>inherits</i> from its direct superclass and direct superinterfaces all the methods
(whether <code>abstract</code> or not) of the superclass and superinterfaces that are 
accessible to code in the class and are neither overridden <a href="8.doc.html#227927">(&#167;8.4.6.1)</a> nor hidden 
<a href="8.doc.html#227928">(&#167;8.4.6.2)</a> by a declaration in the class.
<p><a name="227927"></a>
<h4>8.4.6.1    Overriding (By Instance Methods)</h4>
<a name="39521"></a>
If a class declares an instance method, then the declaration of that method is said 
to <i>override</i> any and all methods with the same signature in the superclasses and 
superinterfaces of the class that would otherwise be accessible to code in the class. 
Moreover, if the method declared in the class is not <code>abstract</code>, then the declaration
of that method is said to <i>implement</i> any and all declarations of <code>abstract</code> 
methods with the same signature in the superclasses and superinterfaces of the 
class that would otherwise be accessible to code in the class.
<p><a name="227929"></a>
A compile-time error occurs if an instance method overrides a <code>static</code> method. In this respect, overriding of methods differs from hiding of fields <a href="8.doc.html#40898">(&#167;8.3)</a>, for it is permissible for an instance variable to hide a <code>static</code> variable.<p>
<a name="227988"></a>
An overridden method can be accessed by using a method invocation expression <a href="15.doc.html#20448">(&#167;15.11)</a> that contains the keyword <code>super</code>. Note that a qualified name or a cast to a superclass type is not effective in attempting to access an overridden method; in this respect, overriding of methods differs from hiding of fields. See <a href="15.doc.html#239751">&#167;15.11.4.10</a> for discussion and examples of this point.<p>
<a name="227928"></a>
<h4>8.4.6.2    Hiding (By Class Methods)</h4>
<a name="227961"></a>
If a class declares a <code>static</code> method, then the declaration of that method is said to 
<i>hide</i> any and all methods with the same signature in the superclasses and superinterfaces
of the class that would otherwise be accessible to code in the class. A 
compile-time error occurs if a <code>static</code> method hides an instance method. In this 
respect, hiding of methods differs from hiding of fields <a href="8.doc.html#40898">(&#167;8.3)</a>, for it is permissible 
for a <code>static</code> variable to hide an instance variable.
<p><a name="227976"></a>
A hidden method can be accessed by using a qualified name or by using a method invocation expression <a href="15.doc.html#20448">(&#167;15.11)</a> that contains the keyword <code>super</code> or a cast to a superclass type. In this respect, hiding of methods is similar to hiding of fields.<p>
<a name="227965"></a>
<h4>8.4.6.3    Requirements in Overriding and Hiding</h4>
<a name="227966"></a>
If a method declaration overrides or hides the declaration of another method, then 
a compile-time error occurs if they have different return types or if one has a 
return type and the other is <code>void</code>. Moreover, a method declaration must not have a 
<code>throws</code> clause that conflicts <a href="8.doc.html#78323">(&#167;8.4.4)</a> with that of any method that it overrides or 
hides; otherwise, &#32;a compile-time error occurs. In these respects, overriding of 
methods differs from hiding of fields <a href="8.doc.html#40898">(&#167;8.3)</a>, for it is permissible for a field to hide 
a field of another type.
<p><a name="39548"></a>
The access modifier <a href="6.doc.html#33916">(&#167;6.6)</a> of an overriding or hiding method must provide at least as much access as the overridden or hidden method, or a compile-time error occurs. In more detail:<p>
<ul><a name="39549"></a>
<li>If the overridden or hidden method is <code>public</code>, then the overriding or hiding method must be <code>public</code>; otherwise, a compile-time error occurs.
<a name="39550"></a>
<li>If the overridden or hidden method is <code>protected</code>, then the overriding or hiding method must be <code>protected</code> or <code>public</code>; otherwise, a compile-time error occurs.
<a name="39551"></a>
<li>If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be <code>private</code>; otherwise, a compile-time error occurs.
</ul><a name="39552"></a>
Note that a <code>private</code> method is never accessible to subclasses and so cannot be 
hidden or overridden in the technical sense of those terms. This means that a subclass
can declare a method with the same signature as a <code>private</code> method in one of 
its superclasses, and there is no requirement that the return type or <code>throws</code> clause 
of such a method bear any relationship to those of the <code>private</code> method in the 
superclass.
<p><a name="227941"></a>
<h4>8.4.6.4    Inheriting Methods with the Same Signature</h4>
<a name="39557"></a>
It is possible for a class to inherit more than one method with the same signature 
<a href="8.doc.html#227941">(&#167;8.4.6.4)</a>. Such a situation does not in itself cause a compile-time error. There are 
then two possible cases:
<p><ul><a name="39561"></a>
<li>If one of the inherited methods is not <code>abstract</code>, then there are two subcases:
<ul>
<a name="39562"></a>
<li>If the method that is not <code>abstract</code> is <code>static</code>, a compile-time error occurs.
<a name="39563"></a>
<li>Otherwise, the method that is not <code>abstract</code> is considered to override, and therefore to implement, all the other methods on behalf of the class that inherits it. A compile-time error occurs if, comparing the method that is not <code>abstract</code> with each of the other of the inherited methods, for any such pair, either they have different return types or one has a return type and the other is <code>void</code>. Moreover, a compile-time error occurs if the inherited method that is not <code>abstract</code> has a <code>throws</code> clause that conflicts <a href="8.doc.html#78323">(&#167;8.4.4)</a> with that of any other of the inherited methods.
</ul>
<a name="39567"></a>
<li>If none of the inherited methods is not <code>abstract</code>, then the class is necessarily an <code>abstract</code> class and is considered to inherit all the <code>abstract</code> methods. A compile-time error occurs if, for any two such inherited methods, either they have different return types or one has a return type and the other is <code>void</code>. (The <code>throws</code> clauses do not cause errors in this case.)
</ul><a name="39568"></a>
It is not possible for two or more inherited methods with the same signature not to 
be <code>abstract</code>, because methods that are not <code>abstract</code> are inherited only from the 
direct superclass, not from superinterfaces.
<p><a name="39569"></a>
There might be several paths by which the same method declaration might be inherited from an interface. This fact causes no difficulty and never, of itself, results in a compile-time error.<p>
<a name="227768"></a>
<h3>8.4.7    Overloading</h3>
<a name="39587"></a>
If two methods of a class (whether both declared in the same class, or both inherited
by a class, or one declared and one inherited) have the same name but different
signatures, then the method name is said to be <i>overloaded</i>. This fact causes no 
difficulty and never of itself results in a compile-time error. There is no required 
relationship between the return types or between the <code>throws</code> clauses of two methods
with the same name but different signatures.
<p><a name="39909"></a>
Methods are overridden on a signature-by-signature basis. If, for example, a class declares two <code>public</code> methods with the same name, and a subclass overrides one of them, the subclass still inherits the other method. In this respect, Java differs from C++.<p>
<a name="39591"></a>
When a method is invoked <a href="15.doc.html#20448">(&#167;15.11)</a>, the number of actual arguments and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked <a href="15.doc.html#21693">(&#167;15.11.2)</a>. If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup <a href="15.doc.html#45677">(&#167;15.11.4)</a>.<p>
<a name="39598"></a>
<h3>8.4.8    Examples of Method Declarations</h3>
<a name="39599"></a>
The following examples illustrate some (possibly subtle) points about method 
declarations.
<p><a name="39600"></a>
<h4>8.4.8.1    Example: Overriding</h4>
<a name="39601"></a>
In the example:
<p><pre><a name="39602"></a>
class Point {
<br><a name="39603"></a>	int x = 0, y = 0;
<br><br><a name="39604"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<br><a name="39605"></a>}
<br><a name="39606"></a>
class SlowPoint extends Point {
<br><a name="39607"></a>	int xLimit, yLimit;
<br><a name="39608"></a>
	void move(int dx, int dy) {
<a name="39609"></a>		super.move(limit(dx, xLimit), limit(dy, yLimit));
<a name="39610"></a>	}
<br><a name="39611"></a>
	static int limit(int d, int limit) {
<a name="39612"></a>		return d &gt; limit ? limit : d &lt; -limit ? -limit : d;
<a name="39613"></a>	}
<br><a name="39614"></a>}
</pre><a name="39615"></a>
the class <code>SlowPoint</code> overrides the declarations of method <code>move</code> of class <code>Point</code> 
with its own <code>move</code> method, which limits the distance that the point can move on 
each invocation of the method. When the <code>move</code> method is invoked for an instance 
of class <code>SlowPoint</code>, the overriding definition in class <code>SlowPoint</code> will always be 
called, even if the reference to the <code>SlowPoint</code> object is taken from a variable 
whose type is <code>Point</code>.
<p><a name="39617"></a>
<h4>8.4.8.2    Example: Overloading, Overriding, and Hiding</h4>
<a name="39618"></a>
In the example:
<p><pre><a name="39619"></a>
class Point {
<br><a name="39620"></a>	int x = 0, y = 0;
<br><br><a name="39621"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<br><br><a name="39622"></a>	int color;
<br><a name="39623"></a>}
<br><a name="39624"></a>
class RealPoint extends Point {
<br><a name="39625"></a>	float x = 0.0f, y = 0.0f;
<br><br><a name="39626"></a>	void move(int dx, int dy) { move((float)dx, (float)dy); }
<br><br><a name="39627"></a>	void move(float dx, float dy) { x += dx; y += dy; }
<br><a name="39628"></a>}
</pre><a name="39629"></a>
the class <code>RealPoint</code> hides the declarations of the <code>int</code> instance variables <code>x</code> and <code>y</code> 
of class <code>Point</code> with its own <code>float</code> instance variables <code>x</code> and <code>y</code>, and overrides the 
method <code>move</code> of class <code>Point</code> with its own <code>move</code> method. It also overloads the name 
<code>move</code> with another method with a different signature <a href="8.doc.html#38649">(&#167;8.4.2)</a>.
<p><a name="39633"></a>
In this example, the members of the class <code>RealPoint</code> include the instance variable <code>color</code> inherited from the class <code>Point</code>, the <code>float</code> instance variables <code>x</code> and <code>y</code> declared in <code>RealPoint</code>, and the two <code>move</code> methods declared in <code>RealPoint</code>.<p>
<a name="39634"></a>
Which of these overloaded <code>move</code> methods of class <code>RealPoint</code> will be chosen for any particular method invocation will be determined at compile time by the overloading resolution procedure described in <a href="15.doc.html#20448">&#167;15.11</a>.<p>
<a name="39638"></a>
<h4>8.4.8.3    Example: Incorrect Overriding</h4>
<a name="39639"></a>
This example is an extended variation of that in the preceding section:
<p><pre><a name="39640"></a>
class Point {
<br><a name="39641"></a>	int x = 0, y = 0, color;
<br><br><a name="39642"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<br><br><a name="39643"></a>	int getX() { return x; }
<br><br><a name="39644"></a>	int getY() { return y; }
<br><a name="39646"></a>}
<br><a name="39647"></a>
class RealPoint extends Point {
<br><a name="39648"></a>	float x = 0.0f, y = 0.0f;
<br><br><a name="39649"></a>	void move(int dx, int dy) { move((float)dx, (float)dy); }
<br><br><a name="39650"></a>	void move(float dx, float dy) { x += dx; y += dy; }
<br><br><a name="39651"></a>	float getX() { return x; }
<br><br><a name="39652"></a>	float getY() { return y; }
<br><a name="39653"></a>}
</pre><a name="39654"></a>
Here the class <code>Point</code> provides methods <code>getX</code> and <code>getY</code> that return the values of its 
fields <code>x</code> and <code>y</code>; the class <code>RealPoint</code> then overrides these methods by declaring 
methods with the same signature. The result is two errors at compile time, one for 
each method, because the return types do not match; the methods in class <code>Point</code> 
return values of type <code>int</code>, but the wanna-be overriding methods in class 
<code>RealPoint</code> return values of type <code>float</code>.
<p><a name="39655"></a>
<h4>8.4.8.4    Example: Overriding versus Hiding</h4>
<a name="39656"></a>
This example corrects the errors of the example in the preceding section:
<p><pre><a name="39657"></a>
class Point {
<br><a name="39658"></a>	int x = 0, y = 0;
<br><br><a name="39659"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<br><br><a name="39660"></a>	int getX() { return x; }
<br><br><a name="39661"></a>	int getY() { return y; }
<br><br><a name="39662"></a>	int color;
<br><a name="39663"></a>}
<br><a name="39664"></a>
class RealPoint extends Point {
<br><a name="39665"></a>	float x = 0.0f, y = 0.0f;
<br><br><a name="39666"></a>	void move(int dx, int dy) { move((float)dx, (float)dy); }
<br><br><a name="39667"></a>	void move(float dx, float dy) { x += dx; y += dy; }
<br><br><a name="39668"></a>	int getX() { return (int)Math.floor(x); }
<br><br><a name="39669"></a>	int getY() { return (int)Math.floor(y); }
<br><a name="39670"></a>}
</pre><a name="39671"></a>
Here the overriding methods <code>getX</code> and <code>getY</code> in class <code>RealPoint</code> have the same 
return types as the methods of class <code>Point</code> that they override, so this code can be 
successfully compiled.
<p><a name="39672"></a>
Consider, then, this test program:<p>
<pre><a name="39673"></a>
class Test {
<a name="39674"></a>
	public static void main(String[] args) {
<a name="39675"></a>		RealPoint rp = new RealPoint();
<a name="39676"></a>		Point p = rp;
<a name="39677"></a>		rp.move(1.71828f, 4.14159f);
<a name="39678"></a>		p.move(1, -1);
<a name="39679"></a>		show(p.x, p.y);
<a name="39680"></a>		show(rp.x, rp.y);
<a name="39681"></a>		show(p.getX(), p.getY());
<a name="39682"></a>		show(rp.getX(), rp.getY());
<a name="39683"></a>	}
<br><a name="39684"></a>
	static void show(int x, int y) {
<a name="39685"></a>		System.out.println("(" + x + ", " + y + ")");
<a name="39686"></a>	}
<br><a name="39687"></a>
	static void show(float x, float y) {
<a name="39688"></a>		System.out.println("(" + x + ", " + y + ")");
<a name="39689"></a>	}
<br><a name="39690"></a>}
</pre><a name="39691"></a>
The output from this program is:
<p><pre><a name="39692"></a>
(0, 0)
<a name="39693"></a>(2.7182798, 3.14159)
<a name="39694"></a>(2, 3)
<a name="39695"></a>(2, 3)
</pre><a name="39696"></a>
The first line of output illustrates the fact that an instance of <code>RealPoint</code> actually contains the two integer fields declared in class <code>Point</code>; it is just that their names are hidden from code that occurs within the declaration of class <code>RealPoint</code> (and those of any subclasses it might have). When a reference to an instance of class <code>RealPoint</code> in a variable of type <code>Point</code> is used to access the field <code>x</code>, the integer field <code>x</code> declared in class <code>Point</code> is accessed. The fact that its value is zero indicates that the method invocation <code>p.move(1,</code> <code>-1)</code> did not invoke the method <code>move</code> of class <code>Point</code>; instead, it invoked the overriding method <code>move</code> of class <code>RealPoint</code>.<p>
<a name="39697"></a>
The second line of output shows that the field access <code>rp.x</code> refers to the field <code>x</code> declared in class <code>RealPoint</code>. This field is of type <code>float</code>, and this second line of output accordingly displays floating-point values. Incidentally, this also illustrates the fact that the method name <code>show</code> is overloaded; the types of the arguments in the method invocation dictate which of the two definitions will be invoked.<p>
<a name="230120"></a>
The last two lines of output show that the method invocations <code>p.getX()</code> and <code>rp.getX()</code> each invoke the <code>getX</code> method declared in class <code>RealPoint</code>. Indeed, there is no way to invoke the <code>getX</code> method of class <code>Point</code> for an instance of class <code>RealPoint</code> from outside the body of <code>RealPoint</code>, no matter what the type of the variable we may use to hold the reference to the object. Thus, we see that fields and methods behave differently: hiding is different from overriding.<p>
<a name="229207"></a>
<h4>8.4.8.5    Example: Invocation of Hidden Class Methods</h4>
<a name="229208"></a>
A hidden class (<code>static</code>) method can be invoked by using a reference whose type 
is the class that actually contains the declaration of the method. In this respect, 
hiding of static methods is different from overriding of instance methods. The 
example:
<p><a name="229226"></a>
<p>
<a name="229227"></a>
<p>
<a name="229228"></a>
<p>
<pre><a name="229209"></a>
class Super {
<a name="229210"></a>	static String greeting() { return "Goodnight"; }
<a name="229211"></a>	String name() { return "Richard"; }
<a name="229212"></a>}
<br><a name="229213"></a>
class Sub extends Super {
<a name="229214"></a>	static String greeting() { return "Hello"; }
<a name="229215"></a>	String name() { return "Dick"; }
<a name="229216"></a>}
<br><a name="229217"></a>
class Test {
<a name="229218"></a>	public static void main(String[] args) {
<a name="229219"></a>		Super s = new Sub();
<a name="229220"></a>		System.out.println(s.greeting() + ", " + s.name());
<a name="229221"></a>	}
<a name="229222"></a>}
</pre><a name="229223"></a>
produces the output:
<p><pre><a name="229224"></a>Goodnight, Dick
</pre><a name="229225"></a>
because the invocation of <code>greeting</code> uses the type of <code>s</code>, namely <code>Super</code>, to figure 
out, at compile time, which class method to invoke, whereas the invocation of 
<code>name</code> uses the class of <code>s</code>, namely <code>Sub</code>, to figure out, at run time, which instance 
method to invoke.
<p><a name="229149"></a>
<h4>8.4.8.6    Large Example of Overriding</h4>
<a name="229150"></a>
Overriding makes it easy for subclasses to extend the behavior of an existing 
class, as shown in this example:
<p><pre><br><a name="229151"></a>import java.io.OutputStream;
<br><br><a name="229152"></a>import java.io.IOException;
<br></pre><pre><a name="229153"></a>
class BufferOutput {
<br><a name="229154"></a>	private OutputStream o;
<br><br><a name="229155"></a>	BufferOutput(OutputStream o) { this.o = o; }
<br><br><a name="229156"></a>	protected byte[] buf = new byte[512];
<br><br><a name="229157"></a>	protected int pos = 0;
<br><a name="229158"></a>
	public void putchar(char c) throws IOException {
<a name="229159"></a>		if (pos == buf.length)
<a name="229160"></a>			flush();
<a name="229161"></a>		buf[pos++] = (byte)c;
<a name="229162"></a>	}
<br></pre><pre><a name="229163"></a>
	public void putstr(String s) throws IOException {
<a name="229164"></a>		for (int i = 0; i &lt; s.length(); i++)
<a name="229165"></a>			putchar(s.charAt(i));
<a name="229166"></a>	}
<br><a name="229167"></a>
	public void flush() throws IOException {
<a name="229168"></a>		o.write(buf, 0, pos);
<a name="229169"></a>		pos = 0;
<a name="229170"></a>	}
<br><a name="229171"></a>}
<br><a name="229172"></a>
class LineBufferOutput extends BufferOutput {
<br><a name="229173"></a>	LineBufferOutput(OutputStream o) { super(o); }
<br><a name="229174"></a>
	public void putchar(char c) throws IOException {
<a name="229175"></a>		super.putchar(c);
<a name="229176"></a>		if (c == '\n')
<a name="229177"></a>			flush();
<a name="229178"></a>	}
<br><a name="229179"></a>}
<br><a name="229180"></a>
class Test {
<a name="229181"></a>	public static void main(String[] args)<br>
		throws IOException<br>
	{
<a name="229182"></a>		LineBufferOutput lbo =<br>
			new LineBufferOutput(System.out);
<a name="229183"></a>		lbo.putstr("lbo\nlbo");
<a name="229184"></a>		System.out.print("print\n");
<a name="229185"></a>		lbo.putstr("\n");
<a name="229186"></a>	}
<a name="229187"></a>}
</pre><a name="229188"></a>
This example produces the output:
<p><pre><a name="229189"></a>
lbo
<a name="229190"></a>print
<a name="229191"></a>lbo
</pre><a name="229192"></a>
The class <code>BufferOutput</code> implements a very simple buffered version of an <code>OutputStream</code>, flushing the output when the buffer is full or <code>flush</code> is invoked. The subclass <code>LineBufferOutput</code> declares only a constructor and a single method <code>putchar</code>, which overrides the method <code>putchar</code> of <code>BufferOutput</code>. It inherits the methods <code>putstr</code> and <code>flush</code> from class <code>Buffer</code>.<p>
<a name="229193"></a>
In the <code>putchar</code> method of a <code>LineBufferOutput</code> object, if the character argument is a newline, then it invokes the <code>flush</code> method. The critical point about overriding in this example is that the method <code>putstr</code>, which is declared in class <code>BufferOutput</code>, invokes the <code>putchar</code> method defined by the current object <code>this</code>, which is not necessarily the <code>putchar</code> method declared in class <code>BufferOutput</code>.<p>
<a name="229194"></a>
Thus, when <code>putstr</code> is invoked in <code>main</code> using the <code>LineBufferOutput</code> object <code>lbo</code>, the invocation of <code>putchar</code> in the body of the <code>putstr</code> method is an invocation of the <code>putchar</code> of the object <code>lbo</code>, the overriding declaration of <code>putchar</code> that checks for a newline. This allows a subclass of <code>BufferOutput</code> to change the behavior of the <code>putstr</code> method without redefining it.<p>
<a name="229195"></a>
Documentation for a class such as <code>BufferOutput</code>, which is designed to be extended, should clearly indicate what is the contract between the class and its subclasses, and should clearly indicate that subclasses may override the <code>putchar</code> method in this way. The implementor of the <code>BufferOutput</code> class would not, therefore, want to change the implementation of <code>putstr</code> in a future implementation of <code>BufferOutput</code> not to use the method <code>putchar</code>, because this would break the preexisting contract with subclasses. See the further discussion of binary compatibility in <a href="13.doc.html#44871">&#167;13</a>, especially <a href="13.doc.html#44952">&#167;13.2</a>.<p>
<a name="229203"></a>
<h4>8.4.8.7    Example: Incorrect Overriding because of Throws</h4>
<a name="39701"></a>
This example uses the usual and conventional form for declaring a new exception 
type, in its declaration of the class <code>BadPointException</code>:
<p><pre><a name="39702"></a>
class BadPointException extends Exception {
<a name="39703"></a>	BadPointException() { super(); }
<a name="39704"></a>	BadPointException(String s) { super(s); }
<a name="39705"></a>}
<a name="39707"></a>
class Point {
<a name="39708"></a>	int x, y;
<a name="39709"></a>	void move(int dx, int dy) { x += dx; y += dy; }
<a name="39710"></a>}
<br><a name="39711"></a>
class CheckedPoint extends Point {
<a name="39712"></a>	void move(int dx, int dy) throws BadPointException {
<a name="39713"></a>		if ((x + dx) &lt; 0 || (y + dy) &lt; 0)
<a name="39714"></a>			throw new BadPointException();
<a name="39715"></a>		x += dx; y += dy;
<a name="39716"></a>	}
<a name="39717"></a>}
</pre><a name="39718"></a>
This example results in a compile-time error, because the override of method 
<code>move</code> in class <code>CheckedPoint</code> declares that it will throw a checked exception that 
the <code>move</code> in class <code>Point</code> has not declared. If this were not considered an error, an 
invoker of the method <code>move</code> on a reference of type <code>Point</code> could find the contract 
between it and <code>Point</code> broken if this exception were thrown.
<p><a name="39725"></a>
Removing the <code>throws</code> clause does not help:<p>
<pre><a name="39726"></a>
class CheckedPoint extends Point {
<a name="39727"></a>	void move(int dx, int dy) {
<a name="39728"></a>		if ((x + dx) &lt; 0 || (y + dy) &lt; 0)
<a name="39729"></a>			throw new BadPointException();
<a name="39730"></a>		x += dx; y += dy;
<a name="39731"></a>	}
<a name="39732"></a>}
</pre><a name="41194"></a>
A different compile-time error now occurs, because the body of the method <code>move</code> 
cannot throw a checked exception, namely <code>BadPointException</code>, that does not 
appear in the <code>throws</code> clause for <code>move</code>.
<p><a name="39245"></a>
<h2>8.5    Static Initializers</h2>
<a name="39251"></a>
Any <i>static initializers </i>declared in a class are executed when the class is initialized 
and, together with any field initializers <a href="8.doc.html#24510">(&#167;8.3.2)</a> for class variables, may be used to 
initialize the class variables of the class <a href="12.doc.html#44557">(&#167;12.4)</a>.
<p><ul><pre>
<i>StaticInitializer:<br>
</i>	<code>static </code><i>Block
</i></pre></ul><a name="41620"></a>
It is a compile-time error for a static initializer to be able to complete abruptly (<a href="14.doc.html#5894">&#167;14.1</a>, <a href="15.doc.html#79448">&#167;15.5</a>) with a checked exception <a href="11.doc.html#44121">(&#167;11.2)</a>.<p>
<a name="16723"></a>
The static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope. This restriction is designed to catch, at compile time, circular or otherwise malformed initializations. Thus, both:<p>
<pre><a name="24644"></a>
class Z {
<a name="24645"></a>	static int i = j + 2; 
<a name="24646"></a>	static int j = 4;
<a name="24647"></a>}
</pre><a name="24648"></a>
and:
<p><pre><a name="24649"></a>
class Z {
<a name="24651"></a>	static { i = j + 2; }
<a name="229866"></a>	static int i, j;
<a name="24652"></a>	static { j = 4; }
<a name="24653"></a>}
</pre><a name="24654"></a>
result in compile-time errors. 
<p><a name="229805"></a>
Accesses to class variables by methods are not checked in this way, so:
<p><pre><a name="45892"></a>
class Z {
<a name="25680"></a>	static int peek() { return j; }<br>
	static int i = peek();
<a name="41686"></a>	static int j = 1;
<a name="41687"></a>}
<br><a name="41688"></a>
class Test {
<a name="25681"></a>	public static void main(String[] args) {
<a name="41689"></a>		System.out.println(Z.i);
<a name="41690"></a>	}<br>
}
</pre><a name="41691"></a>
produces the output:
<p><pre><a name="41692"></a>0
</pre><a name="41693"></a>
because the variable initializer for <code>i</code> uses the class method <code>peek</code> to access the 
value of the variable <code>j</code> before <code>j</code> has been initialized by its variable initializer, at 
which point it still has its default value <a href="4.doc.html#10931">(&#167;4.5.4)</a>.
<p><a name="41700"></a>
If a <code>return</code> statement <a href="14.doc.html#6767">(&#167;14.15)</a> appears anywhere within a static initializer, then a compile-time error occurs.<p>
<a name="39966"></a>
If the keyword <code>this</code> <a href="15.doc.html#31980">(&#167;15.7.2)</a> or the keyword <code>super</code> (<a href="15.doc.html#41267">&#167;15.10</a>, <a href="15.doc.html#20448">&#167;15.11</a>) appears anywhere within a static initializer, then a compile-time error occurs.<p>
<a name="41652"></a>
<h2>8.6    Constructor Declarations</h2>
<a name="78391"></a>
A <i>constructor</i> is used in the creation of an object that is an instance of a class:
<p><ul><pre>
<i>ConstructorDeclaration:<br>
	ConstructorModifiers</i><sub><i>opt</i></sub><code>&#32;</code><i>ConstructorDeclarator<br>
</i>		<i>Throws</i><sub><i>opt</i></sub><code>&#32;</code><i>ConstructorBody
</i>
<i>ConstructorDeclarator:<br>
</i><code>	</code><i>SimpleTypeName</i><code> ( </code><i>FormalParameterList</i><sub><i>opt</i></sub><code> )
</code></pre></ul><a name="30689"></a>
The <i>SimpleTypeName </i>in the <i>ConstructorDeclarator</i> must be the simple name of 
the class that contains the constructor declaration; otherwise a compile-time error 
occurs. In all other respects, the constructor declaration looks just like a method 
declaration that has no result type.
<p><a name="229249"></a>
Here is a simple example:<p>
<pre><a name="30690"></a>
class Point {
<a name="30691"></a>	int x, y;
<a name="30692"></a>	Point(int x, int y) { this.x = x; this.y = y; }
<a name="30693"></a>}
</pre><a name="41721"></a>
Constructors are invoked by class instance creation expressions <a href="15.doc.html#41147">(&#167;15.8)</a>, by the <code>newInstance</code> method of class <code>Class</code> <a href="javalang.doc2.html#14342">(&#167;20.3)</a>, by the conversions and concatenations caused by the string concatenation operator + <a href="15.doc.html#39990">(&#167;15.17.1)</a>, and by explicit constructor invocations from other constructors <a href="8.doc.html#78435">(&#167;8.6.5)</a>. Constructors are never invoked by method invocation expressions <a href="15.doc.html#20448">(&#167;15.11)</a>. <p>
<a name="29483"></a>
Access to constructors is governed by access modifiers <a href="6.doc.html#33916">(&#167;6.6)</a>. This is useful, for example, in preventing instantiation by declaring an inaccessible constructor <a href="8.doc.html#16830">(&#167;8.6.8)</a>.<p>
<a name="39897"></a>
Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.<p>
<a name="29488"></a>
<h3>8.6.1    Formal Parameters</h3>
<a name="41970"></a>
The formal parameters of a constructor are identical in structure and behavior to 
the formal parameters of a method <a href="8.doc.html#38698">(&#167;8.4.1)</a>.
<p><a name="41990"></a>
<h3>8.6.2    Constructor Signature</h3>
<a name="41996"></a>
The signature of a constructor is identical in structure and behavior to the signature
of a method <a href="8.doc.html#38649">(&#167;8.4.2)</a>.
<p><a name="42018"></a>
<h3>8.6.3    Constructor Modifiers</h3>
<ul><pre>
<i>ConstructorModifiers:<br>
	ConstructorModifier<br>
	ConstructorModifiers</i><code> </code><i>ConstructorModifier
</i>
<i>ConstructorModifier: one of<br>
	</i><code>public&#32;protected&#32;private
</code></pre></ul><a name="36010"></a>
The access modifiers <code>public</code>, <code>protected</code>, and <code>private</code> are discussed in <a href="6.doc.html#33916">&#167;6.6</a>. 
A &#32;compile-time error occurs if the same modifier appears more than once in a 
constructor declaration, or if a constructor declaration has more than one of the 
access modifiers <code>public</code>, <code>protected</code>, and <code>private</code>.
<p><a name="244609"></a>
Unlike methods, a constructor cannot be <code>abstract</code>, <code>static</code>, <code>final</code>, <code>native</code>, or <code>synchronized</code>. A constructor is not inherited, so there is no need to declare it <code>final</code> and an <code>abstract</code> constructor could never be implemented. A constructor is always invoked with respect to an object, so it makes no sense for a constructor to be <code>static</code>. There is no practical need for a constructor to be <code>synchronized</code>, because it would lock the object under construction, which is normally not made available to other threads until all constructors for the object have completed their work. The lack of <code>native</code> constructors is an arbitrary language design choice that makes it easy for an implementation of the Java Virtual Machine to verify that superclass constructors are always properly invoked during object creation.<p>
<a name="244611"></a>
<h3>8.6.4    Constructor Throws</h3>
<a name="244612"></a>
The <code>throws</code> clause for a constructor is identical in structure and behavior to the 
<code>throws</code> clause for a method <a href="8.doc.html#78323">(&#167;8.4.4)</a>.
<p><a name="78435"></a>
<h3>8.6.5    Constructor Body</h3>
<a name="42051"></a>
The first statement of a constructor body may be an explicit invocation of another 
constructor of the same class, written as <code>this</code> followed by a parenthesized argument
list, or an explicit invocation of a constructor of the direct superclass, written 
as <code>super</code> followed by a parenthesized argument list.
<p><ul><pre>
<i>ConstructorBody:<br>
</i>	<code>{ </code><i>ExplicitConstructorInvocation</i><sub><i>opt</i></sub><code> </code><i>BlockStatements</i><sub><i>opt</i></sub><code> }
</code>
<i>ExplicitConstructorInvocation:<br>
	</i><code>this ( </code><i>ArgumentList</i><sub><i>opt</i></sub><code> ) ;<br>
	super ( </code><i>ArgumentList</i><sub><i>opt</i></sub><code> ) ;
</code></pre></ul><a name="230283"></a>
It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving <code>this</code>.<p>
<a name="229836"></a>
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class <code>Object</code>, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "<code>super();</code>", an invocation of the constructor of its direct superclass that takes no arguments.<p>
<a name="30734"></a>
Except for the possibility of explicit constructor invocations, the body of a constructor is like the body of a method <a href="8.doc.html#37316">(&#167;8.4.5)</a>. A <code>return</code> statement <a href="14.doc.html#6767">(&#167;14.15)</a> may be used in the body of a constructor if it does not include an expression.<p>
<a name="42056"></a>
In the example:<p>
<pre><a name="42057"></a>
class Point {
<br><a name="16855"></a>	int x, y;
<br><br><a name="40008"></a>	Point(int x, int y) { this.x = x; this.y = y; }
<br><a name="16859"></a>}
<br><a name="16860"></a>
class ColoredPoint extends Point {
<br><a name="16863"></a>	static final int WHITE = 0, BLACK = 1;
<br><br><a name="16861"></a>	int color;
<br><a name="16862"></a>
	ColoredPoint(int x, int y) {
<a name="16868"></a>		this(x, y, WHITE);
<a name="16869"></a>	}
<br><a name="16866"></a>
	ColoredPoint(int x, int y, int color) {
<a name="16867"></a>		super(x, y);<br>
		this.color = color;<br>
	}
<br><a name="16870"></a>}
</pre><a name="16871"></a>
the first constructor of <code>ColoredPoint</code> invokes the second, providing an additional 
argument; the second constructor of <code>ColoredPoint</code> invokes the constructor of its 
superclass <code>Point</code>, passing along the coordinates.
<p><a name="42065"></a>
An explicit constructor invocation statement may not refer to any instance variables or instance methods declared in this class or any superclass, or use <code>this</code> or <code>super</code> in any expression; otherwise, a compile-time error occurs. For example, if the first constructor of <code>ColoredPoint</code> in the example above were changed to:<p>
<pre><a name="16892"></a>
	ColoredPoint(int x, int y) {
<a name="16893"></a>		this(x, y, color);
<a name="16894"></a>	}
</pre><a name="16895"></a>
then a compile-time error would occur, because an instance variable cannot be 
used within a superclass constructor invocation.
<p><a name="229257"></a>
An invocation of the constructor of the direct superclass, whether it actually appears as an explicit constructor invocation statement or is provided automatically <a href="8.doc.html#16823">(&#167;8.6.7)</a>, performs an additional implicit action after a normal return of control from the constructor: all instance variables that have initializers are initialized at that time, in the textual order in which they appear in the class declaration. An invocation of another constructor in the same class using the keyword <code>this</code> does not perform this additional implicit action.<p>
<a name="229264"></a>
<a href="12.doc.html#44670">&#167;12.5</a> describes the creation and initialization of new class instances.<p>
<a name="229266"></a>
<h3>8.6.6    Constructor Overloading</h3>
<a name="16815"></a>
Overloading of constructors is identical in behavior to overloading of methods. 
The overloading is resolved at compile time by each class instance creation 
expression <a href="15.doc.html#41147">(&#167;15.8)</a>.
<p><a name="16823"></a>
<h3>8.6.7    Default Constructor</h3>
<a name="229830"></a>
If a class contains no constructor declarations, then a <i>default constructor</i> that 
takes no parameters is automatically provided:
<p><ul><a name="229831"></a>
<li>If the class being declared is the primordial class <code>Object</code>, then the default constructor has an empty body.
<a name="229832"></a>
<li>Otherwise, the default constructor takes no parameters and simply invokes the superclass constructor with no arguments.
</ul><a name="16772"></a>
A compile-time error occurs if a default constructor is provided by the compiler but the superclass does not have a constructor that takes no arguments.<p>
<a name="16773"></a>
If the class is declared <code>public</code>, then the default constructor is implicitly given the access modifier <code>public</code> <a href="6.doc.html#33916">(&#167;6.6)</a>; otherwise, the default constructor has the default access implied by no access modifier. Thus, the example:<p>
<pre><a name="16778"></a>
public class Point {
<a name="16779"></a>	int x, y;
<a name="16780"></a>}
</pre><a name="16781"></a>
is equivalent to the declaration:
<p><pre><a name="16782"></a>
public class Point {
<a name="16783"></a>	int x, y;
<a name="16784"></a>	public Point() { super(); }
<a name="16785"></a>}
</pre><a name="16786"></a>
where the default constructor is <code>public</code> because the class <code>Point</code> is <code>public</code>.
<p><a name="16830"></a>
<h3>8.6.8    Preventing Instantiation of a Class</h3>
<a name="16831"></a>
A class can be designed to prevent code outside the class declaration from creating
instances of the class by declaring at least one constructor, to prevent the creation
of an implicit constructor, and declaring all constructors to be <code>private</code>. A 
<code>public</code> class can likewise prevent the creation of instances outside its package by 
declaring at least one constructor, to prevent creation of a default constructor with 
<code>public</code> access, and declaring no constructor that is <code>public</code>.
<p><a name="16833"></a>
Thus, in the example:<p>
<pre><a name="16834"></a>
class ClassOnly {
<a name="16835"></a>	private ClassOnly() { }
<a name="16836"></a>	static String just = "only the lonely";
<a name="16837"></a>}
</pre><a name="16838"></a>
the class <code>ClassOnly</code> cannot be instantiated, while in the example:
<p><pre><br><a name="16839"></a>package just;
<br></pre><pre><a name="16840"></a>
public class PackageOnly {
<a name="16841"></a>	PackageOnly() { }
<a name="16842"></a>	String[] justDesserts = { "cheesecake", "ice cream" };
<a name="16843"></a>}
</pre><a name="16844"></a>
the class <code>PackageOnly</code> can be instantiated only within the package <code>just</code>, in 
which it is declared.
<p><a name="244627"></a>
<p>


<hr>
<!-- This inserts footnotes-->
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="7.doc.html">Prev</a> | <a href="9.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<p>
<font size=-1>Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)<br>
<i><a href="jcopyright.doc.html">Copyright &#169 1996 Sun Microsystems, Inc.</a>
All rights reserved</i>
<br>
Please send any comments or corrections via our <a href="http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback">feedback form</a>
</font>
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body></html><html>
<head>
<meta name="collection" content="exclude">

<title>The Java Language Specification
 Interfaces</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
 
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="8.doc.html">Prev</a> | <a href="10.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<hr><br>
 
<a name="238678"></a>
<p><strong>
CHAPTER
 9 </strong></p>
<a name="238680"></a>
<h1>Interfaces</h1>
<hr><p>
<a name="236346"></a>
An interface declaration introduces a new reference type whose members are 
constants and abstract methods. This type has no implementation, but otherwise 
unrelated classes can implement it by providing implementations for its abstract 
methods.
<p><a name="236347"></a>
Java programs can use interfaces to make it unnecessary for related classes to share a common abstract superclass or to add methods to <code>Object</code>.<p>
<a name="19956"></a>
An interface may be declared to be an <i>direct extension </i>of one or more other interfaces, meaning that it implicitly specifies all the abstract methods and constants of the interfaces it extends, except for any constants that it may hide.<p>
<a name="30809"></a>
A class may be declared to <i>directly implement</i> one or more interfaces, meaning that any instance of the class implements all the abstract methods specified by the interface or interfaces. A class necessarily implements all the interfaces that its direct superclasses and direct superinterfaces do. This (multiple) interface inheritance allows objects to support (multiple) common behaviors without sharing any implementation.<p>
<a name="35467"></a>
A variable whose declared type is an interface type may have as its value a reference to any object that is an instance of a class declared to implement the specified interface. It is not sufficient that the class happen to implement all the abstract methods of the interface; the class or one of its superclasses must actually be declared to implement the interface, or else the class is not considered to implement the interface.<p>
<a name="35470"></a>
<h2>9.1    Interface Declarations</h2>
<a name="27727"></a>
An interface declaration specifies a new reference type:
<p><ul><pre>
<i>InterfaceDeclaration:<br>
</i>	<i>InterfaceModifiers</i><sub><i>opt</i></sub><code> interface </code><i>Identifier<br>
</i>		<i>ExtendsInterfaces</i><sub><i>opt</i></sub><code> </code><i>InterfaceBody
</i></pre></ul><a name="235931"></a>
A compile-time error occurs if the <em>Identifier </em>naming an interface appears as the 
name of any other class or interface in the same package. A compile-time error 
also occurs if the <i>Identifier</i> naming an interface appears as the name by which a 
class or interface is to be known via a single-type-import declaration <a href="7.doc.html#26699">(&#167;7.5.1)</a> in 
the compilation unit containing the interface declaration. In the example:
<p><pre><br><a name="17005"></a>class Point { int x, y; }
<br><a name="17006"></a>interface Point { void move(int dx, int dy); }
</pre><a name="17007"></a>
a compile-time error occurs because a <code>class</code> and an <code>interface</code> in the same package
cannot have the same name.
<p><a name="39713"></a>
<h3>9.1.1    Scope of an Interface Type Name</h3>
<a name="235941"></a>
The <i>Identifier</i> specifies the name of the interface and has as its scope the entire 
package in which it is declared. This is the same scoping rule as for class type 
names; see <a href="8.doc.html#39196">&#167;8.1.1</a> for an example involving classes.
<p><a name="235947"></a>
<h3>9.1.2    Interface Modifiers</h3>
<a name="17033"></a>
An interface declaration may be preceded by <i>interface modifiers</i>:
<p><ul><pre>
<i>InterfaceModifiers:<br>
</i><code>	</code><i>InterfaceModifier<br>
</i><code>	</code><i>InterfaceModifiers</i><code> </code><i>InterfaceModifier
</i>
<i>InterfaceModifier:</i> <i>one</i> <i>of<br>
</i><code>	public&#32;abstract
</code></pre></ul><a name="36030"></a>
The access modifier <code>public</code> is discussed in <a href="6.doc.html#33916">&#167;6.6</a>. A compile-time error occurs if 
the same modifier appears more than once in an interface declaration.
<p><a name="30820"></a>
<h4>9.1.2.1    abstract Interfaces</h4>
<a name="30821"></a>
Every interface is implicitly <code>abstract</code>. This modifier is obsolete and should not 
be used in new Java programs.
<p><a name="78598"></a>
<h3>9.1.3    Superinterfaces</h3>
<a name="78599"></a>
If an <code>extends</code> clause is provided, then the interface being declared extends each 
of the other named interfaces and therefore inherits the methods and constants of 
each of the other named interfaces. These other named interfaces are the <i>direct 
superinterfaces</i> of the interface being declared. Any class that <code>implements</code> the 
declared interface is also considered to implement all the interfaces that this interface
<code>extends</code> and that are accessible to the class.
<p><ul><pre>
<i>ExtendsInterfaces:<br>
</i>	<code>extends </code><i>InterfaceType<br>
</i>	<i>ExtendsInterfaces</i><code> , </code><i>InterfaceType
</i></pre></ul><a name="21599"></a>
The following is repeated from <a href="4.doc.html#9317">&#167;4.3</a> to make the presentation here clearer:
<p><ul><pre>
<i>InterfaceType:<br>
</i>	<i>TypeName
</i></pre></ul><a name="152015"></a>
Each <i>InterfaceType </i>in the <code>extends</code> clause of an interface declaration must name an accessible interface type; otherwise a compile-time error occurs.<p>
<a name="152016"></a>
A compile-time error occurs if there is a circularity such that an interface directly or indirectly extends itself.<p>
<a name="78603"></a>
There is no analogue of the class <code>Object</code> for interfaces; that is, while every class is an extension of class <code>Object</code>, there is no single interface of which all interfaces are extensions.<p>
<a name="236095"></a>
The <i>superinterface </i>relationship is the transitive closure of the direct superinterface relationship. An interface <i>K</i><i></i> is a superinterface of interface <i>I</i><i></i> if either of the following is true:<p>
<ul><a name="236096"></a>
<li><i>K</i> is a direct superinterface of <i>I</i><i>.</i>
<a name="236097"></a>
<li>There exists an interface <i>J</i><i></i> such that <i>K</i><i></i> is a superinterface of <i>J</i><i></i>, and <i>J</i><i></i> is a superinterface of <i>I</i><i></i>, applying this definition recursively.
</ul><a name="236428"></a>
Interface <i>I</i><i></i> is said to be a <i>subinterface </i>of interface <i>K</i><i></i> whenever <i>K</i><i> </i>is a superinterface
of <i>I</i><i></i>.
<p><a name="236431"></a>
<h3>9.1.4    Interface Body and Member Declarations</h3>
<a name="78608"></a>
The body of an interface may declare members of the interface:
<p><ul><pre>
<i>InterfaceBody:<br>
</i><code>	{ </code><i>InterfaceMemberDeclarations</i><sub><i>opt</i></sub><code> }
</code>
<i>InterfaceMemberDeclarations:<br>
</i>	<i>InterfaceMemberDeclaration<br>
</i>	<i>InterfaceMemberDeclarations</i><code> </code><i>InterfaceMemberDeclaration
</i>
<i>InterfaceMemberDeclaration:<br>
</i>	<i>ConstantDeclaration<br>
</i>	<i>AbstractMethodDeclaration
</i></pre></ul><a name="17148"></a>
The scope of the name of a member declared in an interface type is the entire body 
of the interface type declaration.
<p><a name="17144"></a>
<h3>9.1.5    Access to Interface Member Names</h3>
<a name="17145"></a>
All interface members are implicitly <code>public</code>. They are accessible outside the 
package where the interface is declared if the interface is also declared <code>public</code> 
and the package containing the interface is accessible as described in <a href="7.doc.html#26535">&#167;7.1</a>.
<p><a name="32392"></a>
<h2>9.2    Interface Members</h2>
<a name="78624"></a>
The members of an interface are those members inherited from direct superinterfaces
and those members declared in the interface.
<p><a name="235920"></a>
The interface inherits, from the interfaces it extends, all members of those interfaces, except for fields that it hides and methods that it overrides.<p>
<a name="78642"></a>
<h2>9.3    Field (Constant) Declarations</h2>
<ul><pre>
<i>ConstantDeclaration:<br>
</i>	<i>ConstantModifiers</i><code> </code><i>Type</i><code> </code><i>VariableDeclarator
</i>
<i>ConstantModifiers:</i> <i>one</i> <i>of<br>
</i>	<code>public&#32;static&#32;final
</code></pre></ul><a name="40575"></a>
Every field declaration in the body of an interface is implicitly <code>public</code>, <code>static</code>, and <code>final</code>. It is permitted, but strongly discouraged as a matter of style, to redundantly specify any or all of these modifiers for such fields.<p>
<a name="40577"></a>
A constant declaration in an interface must not include any of the modifiers <code>synchronized</code>, <code>transient</code>, or <code>volatile</code>, or a compile-time error occurs.<p>
<a name="40725"></a>
It is possible for an interface to inherit more than one field with the same name <a href="8.doc.html#40491">(&#167;8.3.3.3)</a>. Such a situation does not in itself cause a compile-time error. However, any attempt within the body of the interface to refer to either field by its simple name will result in a compile-time error, because such a reference is ambiguous.<p>
<a name="40729"></a>
There might be several paths by which the same field declaration might be inherited from an interface. In such a situation, the field is considered to be inherited only once, and it may be referred to by its simple name without ambiguity.<p>
<a name="40720"></a>
<h3>9.3.1    Initialization of Fields in Interfaces</h3>
<a name="236695"></a>
Every field in the body of an interface must have an initialization expression, 
which need not be a constant expression. The variable initializer is evaluated and 
the assignment performed exactly once, when the interface is initialized <a href="12.doc.html#44557">(&#167;12.4)</a>.
<p><a name="236699"></a>
A compile-time error occurs if an initialization expression for an interface field contains a reference by simple name to the same field or to another field whose declaration occurs textually later in the same interface. Thus:<p>
<pre><a name="41008"></a>
interface Test {
<a name="41009"></a>	float f = j;
<a name="41010"></a>	int j = 1;
<a name="41011"></a>	int k = k+1;
<a name="41012"></a>}
</pre><a name="41013"></a>
causes two compile-time errors, because <code>j</code> is referred to in the initialization of <code>f</code> 
before <code>j</code> is declared and because the initialization of <code>k</code> refers to <code>k</code> itself.
<p><a name="236702"></a>
(One subtlety here is that, at run time, <code>fields</code> that are initialized with compile-time constant values are initialized first. This applies also to <code>static</code> <code>final</code> fields in classes <a href="8.doc.html#38010">(&#167;8.3.2.1)</a>. This means, in particular, that these fields will never be observed to have their default initial values <a href="4.doc.html#10931">(&#167;4.5.4)</a>, even by devious programs. See <a href="12.doc.html#44630">&#167;12.4.2</a> and <a href="13.doc.html#45139">&#167;13.4.8</a> for more discussion.)<p>
<a name="41024"></a>
If the keyword <code>this</code> <a href="15.doc.html#31980">(&#167;15.7.2)</a> or the keyword <code>super</code> (<a href="15.doc.html#20860">15.10.2</a>, <a href="15.doc.html#20448">15.11</a>) occurs in an initialization expression for a field of an interface, then a compile-time error occurs.<p>
<a name="40595"></a>
<h3>9.3.2    Examples of Field Declarations</h3>
<a name="40743"></a>
The following example illustrates some (possibly subtle) points about field declarations.

<p><a name="40596"></a>
<h4>9.3.2.1    Ambiguous Inherited Fields</h4>
<a name="40648"></a>
If two fields with the same name are inherited by an interface because, for example,
two of its direct superinterfaces declare fields with that name, then a single 
<i>ambiguous member</i> results. Any use of this ambiguous member will result in a 
compile-time error. Thus in the example:
<p><pre><a name="40649"></a>
interface BaseColors {
<a name="40650"></a>	int RED = 1, GREEN = 2, BLUE = 4;
<a name="40651"></a>}
<br><a name="40652"></a>
interface RainbowColors extends BaseColors {
<a name="40653"></a>	int YELLOW = 3, ORANGE = 5, INDIGO = 6, VIOLET = 7;
<a name="40654"></a>}
<br><a name="40655"></a>
interface PrintColors extends BaseColors {
<a name="40656"></a>	int YELLOW = 8, CYAN = 16, MAGENTA = 32;
<a name="40657"></a>}
<br><a name="40658"></a>
interface LotsOfColors extends RainbowColors, PrintColors {
<a name="40659"></a>	int FUCHSIA = 17, VERMILION = 43, CHARTREUSE = RED+90;
<a name="40660"></a>}
</pre><a name="40661"></a>
the interface <code>LotsOfColors</code> inherits two fields named <code>YELLOW</code>. This is all right as 
long as the interface does not contain any reference by simple name to the field 
<code>YELLOW</code>. (Such a reference could occur within a variable initializer for a field.)
<p><a name="40696"></a>
Even if interface <code>PrintColors</code> were to give the value <code>3</code> to <code>YELLOW</code> rather than the value <code>8</code>, a reference to field <code>YELLOW</code> within interface <code>LotsOfColors</code> would still be considered ambiguous.<p>
<a name="40599"></a>
<h4>9.3.2.2    Multiply Inherited Fields</h4>
<a name="236005"></a>
If a single field is inherited multiple times from the same interface because, for 
example, both this interface and one of this interface's direct superinterfaces 
extend the interface that declares the field, then only a single member results. This 
situation does not in itself cause a compile-time error. 
<p><a name="236006"></a>
In the example in the previous section, the fields <code>RED</code>, <code>GREEN</code>, and <code>BLUE</code> are inherited by interface <code>LotsOfColors</code> in more than one way, through interface <code>RainbowColors</code> and also through interface <code>PrintColors</code>, but the reference to field <code>RED</code> in interface <code>LotsOfColors</code> is not considered ambiguous because only one actual declaration of the field <code>RED</code> is involved.<p>
<a name="78651"></a>
<h2>9.4    Abstract Method Declarations</h2>
<ul><pre>
<i>AbstractMethodDeclaration:<br>
</i>	<i>AbstractMethodModifiers</i><sub><i>opt</i></sub><code> </code><i>ResultType</i><code> </code><i>MethodDeclarator</i><code> </code><i>Throws</i><sub><i>opt</i></sub><code> ;
</code>
<i>AbstractMethodModifiers:<br>
</i>	<i>AbstractMethodModifier<br>
</i>	<i>AbstractMethodModifiers</i><code> </code><i>AbstractMethodModifier
</i>
<i>AbstractMethodModifier:</i> <i>one</i> <i>of<br>
</i>	<code>public&#32;abstract
</code></pre></ul><a name="36046"></a>
The access modifier <code>public</code> is discussed in <a href="6.doc.html#33916">&#167;6.6</a>. A compile-time error occurs if 
the same modifier appears more than once in an abstract method declaration.
<p><a name="78653"></a>
Every method declaration in the body of an interface is implicitly <code>abstract</code>, so its body is always represented by a semicolon, not a block. For compatibility with older versions of Java, it is permitted but discouraged, as a matter of style, to redundantly specify the <code>abstract</code> modifier for methods declared in interfaces.<p>
<a name="78654"></a>
Every method declaration in the body of an interface is implicitly <code>public</code>. It is permitted, but strongly discouraged as a matter of style, to redundantly specify the <code>public</code> modifier for interface methods.<p>
<a name="38687"></a>
Note that a method declared in an interface must not be declared <code>static</code>, or a compile-time error occurs, because in Java <code>static</code> methods cannot be <code>abstract</code>.<p>
<a name="38689"></a>
Note that a method declared in an interface must not be declared <code>native</code> or <code>synchronized</code>, or a compile-time error occurs, because those keywords describe implementation properties rather than interface properties. However, a method declared in an interface may be implemented by a method that is declared <code>native</code> or <code>synchronized</code> in a class that implements the interface.<p>
<a name="38671"></a>
Note that a method declared in an interface must not be declared <code>final</code> or a compile-time error occurs. However, a method declared in an interface may be implemented by a method that is declared <code>final</code> in a class that implements the interface.<p>
<a name="40247"></a>
<h3>9.4.1    Inheritance and Overriding</h3>
<a name="40229"></a>
If the interface declares a method, then the declaration of that method is said to 
<i>override</i> any and all methods with the same signature in the superinterfaces of the 
interface that would otherwise be accessible to code in this interface.
<p><a name="40233"></a>
If a method declaration in an interface overrides the declaration of a method in another interface, a compile-time error occurs if the methods have different return types or if one has a return type and the other is <code>void</code>. Moreover, a method declaration must not have a <code>throws</code> clause that conflicts <a href="8.doc.html#78323">(&#167;8.4.4)</a> with that of any method that it overrides; otherwise, a compile-time error occurs.<p>
<a name="236025"></a>
Methods are overridden on a signature-by-signature basis. If, for example, an interface declares two <code>public</code> methods with the same name, and a subinterface overrides one of them, the subinterface still inherits the other method.<p>
<a name="40237"></a>
An interface inherits from its direct superinterfaces all methods of the superinterfaces that are not overridden by a declaration in the interface.<p>
<a name="40238"></a>
It is possible for an interface to inherit more than one method with the same signature <a href="8.doc.html#38649">(&#167;8.4.2)</a>. Such a situation does not in itself cause a compile-time error. The interface is considered to inherit all the methods. However, a compile-time error occurs if, for any two such inherited methods, either they have different return types or one has a return type and the other is <code>void</code>. (The <code>throws</code> clauses do not cause errors in this case.)<p>
<a name="40242"></a>
There might be several paths by which the same method declaration is inherited from an interface. This fact causes no difficulty and never of itself results in a compile-time error.<p>
<a name="236017"></a>
<h3>9.4.2    Overloading</h3>
<a name="40243"></a>
If two methods of an interface (whether both declared in the same interface, or 
both inherited by a interface, or one declared and one inherited) have the same 
name but different signatures, then the method name is said to be <i>overloaded</i>. This 
fact causes no difficulty and never of itself results in a compile-time error. There is 
no required relationship between the return types or between the <code>throws</code> clauses 
of two methods with the same name but different signatures.
<p><a name="40248"></a>
<h3>9.4.3    Examples of Abstract Method Declarations</h3>
<a name="40738"></a>
The following examples illustrate some (possibly subtle) points about abstract 
method declarations.
<p><a name="40734"></a>
<h4>9.4.3.1    Example: Overriding</h4>
<a name="40251"></a>
Methods declared in interfaces are <code>abstract</code> and thus contain no implementation. 
About all that can be accomplished by an overriding method declaration, other 
than to affirm a method signature, is to restrict the exceptions that might be thrown 
by an implementation of the method. Here is a variation of the example shown in 
<a href="8.doc.html#34484">&#167;8.4.3.1</a>:
<p><pre><a name="40258"></a>
class BufferEmpty extends Exception {
<a name="40259"></a>	BufferEmpty() { super(); }
<a name="40260"></a>	BufferEmpty(String s) { super(s); }
<a name="40261"></a>}
<br><a name="40262"></a>
class BufferError extends Exception {
<a name="40263"></a>	BufferError() { super(); }
<a name="40264"></a>	BufferError(String s) { super(s); }
<a name="40265"></a>}
<br><a name="40266"></a>
public interface Buffer {
<a name="40267"></a>	char get() throws BufferEmpty, BufferError;
<a name="40268"></a>}
<br><a name="40269"></a>
public interface InfiniteBuffer extends Buffer {
<a name="40270"></a>	 char get() throws BufferError;												// override
<a name="40271"></a>}
</pre><a name="40735"></a>
<h4>9.4.3.2    Example: Overloading</h4>
<a name="40788"></a>
In the example code:
<p><pre><a name="40767"></a>
interface PointInterface {
<a name="40768"></a>	void move(int dx, int dy);
<a name="40770"></a>}
<br><a name="40772"></a>
interface RealPointInterface extends PointInterface {
<a name="40781"></a>	void move(float dx, float dy);
<a name="40783"></a>	void move(double dx, double dy);
<a name="40775"></a>}
</pre><a name="236063"></a>
the method name <code>move</code> is overloaded in interface <code>RealPointInterface</code> with 
three different signatures, two of them declared and one inherited. Any class that 
implements interface <code>RealPointInterface</code> must provide implementations of all 
three method signatures.
<p><a name="244753"></a>
<p>


<hr>
<!-- This inserts footnotes-->
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="8.doc.html">Prev</a> | <a href="10.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<p>
<font size=-1>Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)<br>
<i><a href="jcopyright.doc.html">Copyright &#169 1996 Sun Microsystems, Inc.</a>
All rights reserved</i>
<br>
Please send any comments or corrections via our <a href="http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback">feedback form</a>
</font>
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body></html><html>
<head>
<meta name="collection" content="exclude">

<title>The Java Language Specification
 Arrays</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
 
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="9.doc.html">Prev</a> | <a href="11.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<hr><br>
 
<a name="27803"></a>
<p><strong>
CHAPTER
 10 </strong></p>
<a name="27805"></a>
<h1>Arrays</h1>
<hr><p>
<a name="25550"></a>
Java <i>arrays</i> are objects <a href="4.doc.html#12028">(&#167;4.3.1)</a>, are dynamically created, and may be assigned 
to variables of type <code>Object</code> <a href="4.doc.html#11055">(&#167;4.3.2)</a>. All methods of class <code>Object</code> may be invoked 
on an array.
<p><a name="25500"></a>
An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be <i>empty</i>. The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the <i>components</i> of the array. If an array has <i>n</i> components, we say <i>n</i> is the <i>length</i> of the array; the components of the array are referenced using integer indices from 0 to <img src="10.doc.anc1.gif">, inclusive.<p>
<a name="25501"></a>
All the components of an array have the same type, called the <i>component type</i> of the array. If the component type of an array is <i>T</i>, then the type of the array itself is written <i>T</i><code>[]</code>.<p>
<a name="25502"></a>
The component type of an array may itself be an array type. The components of such an array may contain references to subarrays. If, starting from any array type, one considers its component type, and then (if that is also an array type) the component type of that type, and so on, eventually one must reach a component type that is not an array type; this is called the <i>element type</i> of the original array, and the components at this level of the data structure are called the <i>elements</i> of the original array.<p>
<a name="25514"></a>
There is one situation in which an element of an array can be an array: if the element type is <code>Object</code>, then some or all of the elements may be arrays, because any array object can be assigned to any variable of type <code>Object</code>.<p>
<a name="25518"></a>
<h2>10.1    Array Types</h2>
<a name="25519"></a>
An array type is written as the name of an element type followed by some number 
of empty pairs of square brackets <code>[]</code>. The number of bracket pairs indicates the 
depth of array nesting. An array's length is not part of its type.
<p><a name="30943"></a>
The element type of an array may be any type, whether primitive or reference. In particular:<p>
<ul><a name="26084"></a>
<li>Arrays with an interface type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any class type that implements the interface.
<a name="26075"></a>
<li>Arrays with an <code>abstract</code> class type as the component type are allowed. The elements of such an array may have as their value a null reference or instances of any subclass of the <code>abstract</code> class that is not itself <code>abstract</code>.
</ul><a name="25523"></a>
Array types are used in declarations and in cast expressions <a href="15.doc.html#238146">(&#167;15.15)</a>.<p>
<a name="25891"></a>
<h2>10.2    Array Variables</h2>
<a name="17235"></a>
A variable of array type holds a reference to an object. Declaring a variable of 
array type does not create an array object or allocate any space for array components.
It creates only the variable itself, which can contain a reference to an array. 
However, the initializer part of a declarator <a href="8.doc.html#40898">(&#167;8.3)</a> may create an array, a reference 
to which then becomes the initial value of the variable.
<p><a name="17236"></a>
Because an array's length is not part of its type, a single variable of array type may contain references to arrays of different lengths.<p>
<a name="25894"></a>
Here are examples of declarations of array variables that do not create arrays:<p>
<pre><a name="25895"></a>
int[] ai;							// array of int
<a name="25896"></a>short[][] as;							// array of array of short
<a name="25897"></a>Object[]			ao,				// array of Object
<a name="25898"></a>			otherAo;				// array of Object
<a name="25899"></a>short		s,					// scalar short 
<a name="25901"></a>		aas[][];					// array of array of short
</pre><a name="25902"></a>
Here are some examples of declarations of array variables that create array 
objects:
<p><pre><a name="25903"></a>
Exception ae[] = new Exception[3]; 
<a name="25904"></a>Object aao[][] = new Exception[2][3];
<a name="25905"></a>int[] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
<a name="25906"></a>char ac[] = { 'n', 'o', 't', ' ', 'a', ' ',
<a name="25907"></a>				 '<code>S</code>', 't', 'r', 'i', 'n', 'g' }; 
<a name="25908"></a>String[] aas = { "array", "of", "String", };
</pre><a name="25909"></a>
The <code>[]</code> may appear as part of the type at the beginning of the declaration, or as 
part of the declarator for a particular variable, or both, as in this example:
<p><pre><a name="25910"></a>byte[] rowvector, colvector, matrix[];
</pre><a name="25911"></a>
This declaration is equivalent to:
<p><pre><a name="25929"></a>byte rowvector[], colvector[], matrix[][];
</pre><a name="25915"></a>
Once an array object is created, its length never changes. To make an array variable
refer to an array of different length, a reference to a different array must be 
assigned to the variable.
<p><a name="25953"></a>
If an array variable <i>v</i><i></i> has type <i>A</i><i></i><code>[]</code>, where <i>A</i><i></i> is a reference type, then <i>v</i><i></i> can hold a reference to an instance of any array type <i>B</i><code>[]</code>, provided <i>B</i><i></i> can be assigned to <i>A</i><i></i>. This may result in a run-time exception on a later assignment; see <a href="10.doc.html#11430">&#167;10.10</a> for a discussion.<p>
<a name="25959"></a>
<h2>10.3    Array Creation</h2>
<a name="25650"></a>
An array is created by an array creation expression <a href="15.doc.html#46168">(&#167;15.9)</a> or an array initializer 
<a href="10.doc.html#11358">(&#167;10.6)</a>.
<p><a name="25675"></a>
An array creation expression specifies the element type, the number of levels of nested arrays, and the length of the array for at least one of the levels of nesting. The array's length is available as a final instance variable <code>length</code>.<p>
<a name="25676"></a>
An array initializer creates an array and provides initial values for all its components. (Contrast this with C and C++, where it is possible for an array initializer to specify initial values for some but not all of the components of an array.)<p>
<a name="25566"></a>
<h2>10.4    Array Access</h2>
<a name="53523"></a>
A component of an array is accessed by an array access expression <a href="15.doc.html#239587">(&#167;15.12)</a> that 
consists of an expression whose value is an array reference followed by an indexing
expression enclosed by <code>[</code> and <code>]</code>, as in <code>A[i]</code>. All arrays are <code>0</code>-origin. An array 
with length <i>n</i> can be indexed by the integers <code>0</code> to <i>n</i><code>-1</code>.
<p><a name="25570"></a>
Arrays must be indexed by <code>int</code> values; <code>short</code>, <code>byte</code>, or <code>char</code> values may also be used as index values because they are subjected to unary numeric promotion <a href="5.doc.html#170952">(&#167;5.6.1)</a> and become <code>int</code> values. An attempt to access an array component with a <code>long</code> index value results in a compile-time error.<p>
<a name="53999"></a>
All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an <code>IndexOutOfBoundsException</code> &#32;to be thrown.<p>
<a name="54000"></a>
<h2>10.5    Arrays: A Simple Example</h2>
<a name="25421"></a>
The example:
<p><pre><a name="25422"></a>
class Gauss {
<a name="25426"></a>	public static void main(String[] args) {
<a name="25427"></a>		int[] ia = new int[101];
<a name="25428"></a>		for (int i = 0; i &lt; ia.length; i++)
<a name="25429"></a>			ia[i] = i;
<a name="25435"></a>		int sum = 0;
<a name="25430"></a>		for (int i = 0; i &lt; ia.length; i++)
<a name="25436"></a>			sum += ia[i];
<a name="25443"></a>		System.out.println(sum);
<a name="25444"></a>	}
<a name="25453"></a>}
</pre><a name="25454"></a>
that produces output:
<p><pre><a name="25462"></a>5050
</pre><a name="25463"></a>
declares a variable <code>ia</code> that has type array of <code>int</code>, that is, <code>int[]</code>. The variable <code>ia</code> is 
initialized to reference a newly created array object, created by an array creation 
expression <a href="15.doc.html#46168">(&#167;15.9)</a>. The array creation expression specifies that the array should 
have <code>101</code> components. The length of the array is available using the field <code>length</code>, 
as shown.
<p><a name="25585"></a>
The example program fills the array with the integers from <code>0</code> to <code>100</code>, sums these integers, and prints the result.<p>
<a name="11358"></a>
<h2>10.6    Arrays Initializers</h2>
<a name="25749"></a>
An <i>array initializer</i> may be specified in a declaration, creating an array and providing
some initial values:
<p><ul><pre>
<i>ArrayInitializer:<br>
</i>	<code>{ </code><i>VariableInitializers</i><sub><i>opt</i></sub><code> ,</code><sub><i>opt</i></sub><code> }
</code>
<i>VariableInitializers:<br>
</i>	<i>VariableInitializer<br>
</i>	<i>VariableInitializers</i><code> , </code><i>VariableInitializer
</i></pre></ul><a name="25741"></a>
The following is repeated from <a href="8.doc.html#40898">&#167;8.3</a> to make the presentation here clearer:
<p><ul><pre>
<i>VariableInitializer:<br>
</i>	<i>Expression<br>
</i>	<i>ArrayInitializer
</i></pre></ul><a name="25727"></a>
An array initializer is written as a comma-separated list of expressions, enclosed by braces "<code>{</code>" and "<code>}</code>".<p>
<a name="25754"></a>
The length of the constructed array will equal the number of expressions.<p>
<a name="25755"></a>
Each expression specifies a value for one array component. Each expression must be assignment-compatible <a href="5.doc.html#170768">(&#167;5.2)</a> with the array's component type, or a compile-time error results.<p>
<a name="25756"></a>
If the component type is itself an array type, then the expression specifying a component may itself be an array initializer; that is, array initializers may be nested.<p>
<a name="11390"></a>
A trailing comma may appear after the last expression in an array initializer and is ignored.<p>
<a name="25758"></a>
As an example:<p>
<pre><a name="25759"></a>
class Test {
<a name="25765"></a>	public static void main(String[] args) {
<a name="25760"></a>		int ia[][] = { {1, 2}, null };
<a name="25761"></a>		for (int i = 0; i &lt; 2; i++)
<a name="25762"></a>			for (int j = 0; j &lt; 2; j++)
<a name="25763"></a>				System.out.println(ia[i][j]);
<a name="25766"></a>	}
<a name="25764"></a>}
</pre><a name="25767"></a>
prints:
<p><pre><a name="25769"></a>
1
<a name="25770"></a>2
</pre><a name="25771"></a>
before causing a <code>NullPointerException</code> in trying to index the second component
of the array <code>ia</code>, which is a null reference.
<p><a name="11364"></a>
<h2>10.7    Array Members</h2>
<a name="25782"></a>
The members of an array type are all of the following:
<p><ul><a name="25783"></a>
<li>The <code>public</code> <code>final</code> field <code>length</code>, which contains the number of components of the array (<code>length</code> may be positive or zero)
<a name="42464"></a>
<li>The <code>public</code> method <code>clone</code>, which overrides the method of the same name in class <code>Object</code> and throws no checked exceptions
<a name="25784"></a>
<li>All the members inherited from class <code>Object</code>; the only method of <code>Object</code> that is not inherited is its <code>clone</code> method
</ul><a name="29781"></a>
An array thus has the same methods as the following class:
<p><pre><a name="29785"></a>
class A implements Cloneable {
<a name="29786"></a>	public final int length = <i>X</i>;
<a name="29787"></a>	public Object clone() {
<a name="50155"></a>		try {
<a name="29797"></a>			return super.clone();
<a name="50157"></a>		} catch (CloneNotSupportedException e) {
<a name="29798"></a>			throw new InternalError(e.getMessage());
<a name="29793"></a>		}
<a name="29794"></a>	}
<br><a name="29790"></a>}
</pre><a name="25789"></a>
Every array implements interface <code>Cloneable</code>. That arrays are cloneable is shown 
by the test program:
<p><pre><a name="25795"></a>
class Test {
<a name="25796"></a>	public static void main(String[] args) {
<a name="25801"></a>		int ia1[] = { 1, 2 };
<a name="25802"></a>		int ia2[] = (int[])ia1.clone();
<a name="25803"></a>		System.out.print((ia1 == ia2) + " ");
<a name="25810"></a>		ia1[1]++;
<a name="25811"></a>		System.out.println(ia2[1]);
<a name="25804"></a>	}
<a name="25805"></a>}
</pre><a name="25812"></a>
which prints:
<p><pre><a name="25813"></a>false 2
</pre><a name="25815"></a>
showing that the components of the arrays referenced by <code>ia1</code> and <code>ia2</code> are different 
variables. (In some early implementations of Java this example failed to compile 
because the compiler incorrectly believed that the clone method for an array could 
throw a <code>CloneNotSupportedException</code>.)
<p><a name="25833"></a>
A <code>clone</code> of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared, as shown by the example program:<p>
<pre><a name="25843"></a>
class Test {
<a name="25844"></a>	public static void main(String[] args) throws Throwable {
<a name="25845"></a>		int ia[][] = { { 1 , 2}, null };
<a name="25846"></a>		int ja[][] = (int[][])ia.clone();
<a name="25858"></a>		System.out.print((ia == ja) + " ");
<a name="25847"></a>		System.out.println(ia[0] == ja[0] &amp;&amp; ia[1] == ja[1]);
<a name="25849"></a>	}
<a name="25850"></a>}
</pre><a name="25855"></a>
which prints:
<p><pre><a name="25856"></a>false true
</pre><a name="28553"></a>
showing that the <code>int[]</code> array that is <code>ia[0]</code> and the <code>int[]</code> array that is <code>ja[0]</code> are 
the same array.
<p><a name="40879"></a>
<h2>10.8    <code>Class</code> Objects for Arrays</h2>
<a name="40882"></a>
Every array has an associated <code>Class</code> object, shared with all other arrays with the 
same component type. The superclass of an array type is considered to be <code>Object</code>, 
as shown by the following example code:
<p><pre><a name="40886"></a>
class Test {
<a name="40887"></a>	public static void main(String[] args) {
<a name="40888"></a>		int[] ia = new int[3];
<a name="40889"></a>		System.out.println(ia.getClass());
<a name="40890"></a>		System.out.println(ia.getClass().getSuperclass());
<a name="40891"></a>	}
<a name="40892"></a>}
</pre><a name="40893"></a>
which prints:
<p><pre><a name="40894"></a>
class [I
<a name="40895"></a>class java.lang.Object
</pre><a name="40896"></a>
where the string "<code>[I</code>" is the run-time type signature for the class object "array 
with component type <code>int</code>" <a href="javalang.doc1.html#13783">(&#167;20.1.1)</a>.
<p><a name="25726"></a>
<h2>10.9    An Array of Characters is Not a <code>String</code></h2>
<a name="25730"></a>
In Java, unlike C, an array of <code>char</code> is not a <code>String</code> <a href="javalang.doc11.html#14460">(&#167;20.12)</a>, and neither a <code>String</code> 
nor an array of <code>char</code> is terminated by <code>'\u0000'</code> (the NUL character).
<p><a name="25731"></a>
A Java <code>String</code> object is immutable, that is, its contents never change, while an array of <code>char</code> has mutable elements. The method <code>toCharArray</code> in class <code>String</code> returns an array of characters containing the same character sequence as a <code>String</code>. The class <code>StringBuffer</code> implements useful methods on mutable arrays of characters <a href="javalang.doc12.html#14461">(&#167;20.13)</a>.<p>
<a name="11430"></a>
<h2>10.10    Array Store Exception</h2>
<a name="26003"></a>
If an array variable <i>v</i><i></i> has type <i>A</i><i></i><code>[]</code>, where <i>A</i><i></i> is a reference type, then <i>v</i><i></i> can hold a 
reference to an instance of any array type <i>B</i><code>[]</code>, provided <i>B</i><i></i> can be assigned to <i>A</i><i></i>.
<p><a name="53134"></a>
Thus, the example:<p>
<pre><a name="26004"></a>
class Point { int x, y; }
<br><a name="53558"></a>class ColoredPoint extends Point { int color; }
<br></pre><pre><a name="53993"></a>
class Test {
<a name="26007"></a>	public static void main(String[] args) {
<a name="26008"></a>		ColoredPoint[] cpa = new ColoredPoint[10];
<a name="26009"></a>		Point[] pa = cpa;
<a name="26010"></a>		System.out.println(pa[1] == null);
<a name="26011"></a>		try {
<a name="26012"></a>			pa[0] = new Point();
<a name="26013"></a>		} catch (ArrayStoreException e) {
<a name="26014"></a>			System.out.println(e);
<a name="26015"></a>		}
<a name="26016"></a>	}
<a name="26017"></a>}
</pre><a name="25743"></a>
produces the output:
<p><pre><a name="25746"></a>
true
<a name="25744"></a>java.lang.ArrayStoreException
</pre><a name="26018"></a>
Here the variable <code>pa</code> has type <code>Point[]</code> and the variable <code>cpa</code> has as its value a reference
to an object of type <code>ColoredPoint[]</code>. A <code>ColoredPoint</code> can be assigned 
to a <code>Point</code>; therefore, the value of <code>cpa</code> can be assigned to <code>pa</code>.
<p><a name="26025"></a>
A reference to this array <code>pa</code>, for example, testing whether <code>pa[1]</code> is <code>null</code>, will not result in a run-time type error. This is because the element of the array of type <code>ColoredPoint[]</code> is a <code>ColoredPoint</code>, and every <code>ColoredPoint</code> can stand in for a <code>Point</code>, since <code>Point</code> is the superclass of <code>ColoredPoint</code>.<p>
<a name="26035"></a>
On the other hand, an assignment to the array <code>pa</code> can result in a run-time error. At compile time, an assignment to an element of <code>pa</code> is checked to make sure that the value assigned is a <code>Point</code>. But since <code>pa</code> holds a reference to an array of <code>ColoredPoint</code>, &#32;the assignment is valid only if the type of the value assigned at run-time is, more specifically, a <code>ColoredPoint</code>.<p>
<a name="26044"></a>
Java checks for such a situation at run-time to ensure that the assignment is valid; if not, an <code>ArrayStoreException</code> is thrown. More formally: an assignment to an element of an array whose type is <i>A</i><code>[]</code>, where <i>A</i> is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to <i>A</i>.<p>


<hr>
<!-- This inserts footnotes-->
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="9.doc.html">Prev</a> | <a href="11.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<p>
<font size=-1>Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)<br>
<i><a href="jcopyright.doc.html">Copyright &#169 1996 Sun Microsystems, Inc.</a>
All rights reserved</i>
<br>
Please send any comments or corrections via our <a href="http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback">feedback form</a>
</font>
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body></html><html>
<head>
<meta name="collection" content="exclude">

<title>The Java Language Specification
 Blocks and Statements</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
 
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="13.doc.html">Prev</a> | <a href="15.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<hr><br>
 
<a name="44383"></a>
<p><strong>
CHAPTER
 14 </strong></p>
<a name="101241"></a>
<h1>Blocks and Statements</h1>
<hr><p>
<a name="45234"></a>
The sequence of execution of a Java program is controlled by <i>statements</i>, 
which are executed for their effect and do not have values.
<p><a name="17960"></a>
Some statements <i>contain</i> other statements as part of their structure; such other statements are substatements of the statement. We say that statement <i>S</i><i></i> <i>immediately &#32;contains</i> statement <i>U</i><code></code> if there is no statement <i>T</i><em></em> different from <i>S</i><i></i> and <i>U</i><code></code> such that <i>S</i><i></i> contains <i>T</i><em></em> and <i>T</i><em></em> contains <i>U</i>. In the same manner, some statements contain expressions <a href="15.doc.html#4709">(&#167;15)</a> as part of their structure.<p>
<a name="43082"></a>
The first section of this chapter discusses the distinction between normal and abrupt completion of statements <a href="14.doc.html#5894">(&#167;14.1)</a>. Most of the remaining sections explain the various kinds of statements, describing in detail both their normal behavior and any special treatment of abrupt completion.<p>
<a name="43210"></a>
Blocks are explained first <a href="14.doc.html#24644">(&#167;14.2)</a>, because they can appear in certain places where other kinds of statements are not allowed, and because one other kind of statement, a local variable declaration statement <a href="14.doc.html#5920">(&#167;14.3)</a>, must be immediately contained within a block.<p>
<a name="43203"></a>
Next a grammatical maneuver is explained that sidesteps the familiar "dangling <code>else</code>" problem <a href="14.doc.html#32584">(&#167;14.4)</a>.<p>
<a name="43118"></a>
Statements that will be familiar to C and C++ programmers are the empty <a href="14.doc.html#5970">(&#167;14.5)</a>, labeled <a href="14.doc.html#78993">(&#167;14.6)</a>, expression <a href="14.doc.html#5984">(&#167;14.7)</a>, <code>if</code> <a href="14.doc.html#5991">(&#167;14.8)</a>, <code>switch</code> <a href="14.doc.html#35518">(&#167;14.9)</a>, <code>while</code> <a href="14.doc.html#237277">(&#167;14.10)</a>, <code>do</code> <a href="14.doc.html#6045">(&#167;14.11)</a>, <code>for</code> <a href="14.doc.html#24588">(&#167;14.12)</a>, <code>break</code> <a href="14.doc.html#6842">(&#167;14.13)</a>, <code>continue</code> <a href="14.doc.html#6122">(&#167;14.14)</a>, and <code>return</code> <a href="14.doc.html#6767">(&#167;14.15)</a> statements.<p>
<a name="43199"></a>
Unlike C and C++, Java has no <code>goto</code> statement. However, the <code>break</code> and <code>continue</code> statements are extended in Java to allow them to mention statement labels.<p>
<a name="43200"></a>
The Java statements that are not in the C language are the <code>throw</code> <a href="14.doc.html#237350">(&#167;14.16)</a>, <code>synchronized</code> <a href="14.doc.html#79287">(&#167;14.17)</a>, and <code>try</code> <a href="14.doc.html#79311">(&#167;14.18)</a> statements.<p>
<a name="43110"></a>
The last section <a href="14.doc.html#236365">(&#167;14.19)</a> of this chapter addresses the requirement that every statement be <i>reachable</i> in a certain technical sense.<p>
<a name="5894"></a>
<h2>14.1    Normal and Abrupt Completion of Statements</h2>
<a name="78796"></a>
Every statement has a normal mode of execution in which certain computational 
steps are carried out. The following sections describe the normal mode of execution
for each kind of statement. If all the steps are carried out as described, with no 
indication of abrupt completion, the statement is said to <i>complete normally</i>. However,
certain events may prevent a statement from completing normally:
<p><ul><a name="47062"></a>
<li>The <code>break</code> <a href="14.doc.html#6842">(&#167;14.13)</a>, <code>continue</code> <a href="14.doc.html#6122">(&#167;14.14)</a>, and <code>return</code> <a href="14.doc.html#6767">(&#167;14.15)</a> statements cause a transfer of control that may prevent normal completion of statements that contain them.
<a name="78802"></a>
<li>Evaluation of certain Java expressions may throw exceptions from the Java Virtual Machine; these expressions are summarized in <a href="15.doc.html#79448">&#167;15.5</a>. An explicit <code>throw</code> <a href="14.doc.html#237350">(&#167;14.16)</a> statement also results in an exception. An exception causes a transfer of control that may prevent normal completion of statements.
</ul><a name="5898"></a>
If such an event occurs, then execution of one or more statements may be terminated before all steps of their normal mode of execution have completed; such statements are said to <i>complete abruptly</i>. An abrupt completion always has an associated <i>reason</i>, which is one of the following:<p>
<ul><a name="5899"></a>
<li>A <code>break</code> with no label
<a name="78812"></a>
<li>A <code>break</code> with a given label
<a name="5901"></a>
<li>A <code>continue</code> with no label
<a name="78822"></a>
<li>A <code>continue</code> with a given label
<a name="5903"></a>
<li>A <code>return</code> with no value
<a name="5904"></a>
<li>A <code>return</code> with a given value
<a name="78827"></a>
<li>A <code>throw</code> with a given value, including exceptions thrown by the Java Virtual Machine
</ul><a name="237105"></a>
The terms "complete normally" and "complete abruptly" also apply to the evaluation of expressions <a href="15.doc.html#79448">(&#167;15.5)</a>. The only reason an expression can complete abruptly is that an exception is thrown, because of either a <code>throw</code> with a given value <a href="14.doc.html#237350">(&#167;14.16)</a> or a run-time exception or error (<a href="11.doc.html#44043">&#167;11</a>, <a href="15.doc.html#79448">&#167;15.5</a>).<p>
<a name="237118"></a>
If a statement evaluates an expression, abrupt completion of the expression always causes the immediate abrupt completion of the statement, with the same reason. All succeeding steps in the normal mode of execution are not performed.<p>
<a name="24642"></a>
Unless otherwise specified in this chapter, abrupt completion of a substatement causes the immediate abrupt completion of the statement itself, with the same reason, and all succeeding steps in the normal mode of execution of the statement are not performed.<p>
<a name="24647"></a>
Unless otherwise specified, a statement completes normally if all expressions it evaluates and all substatements it executes complete normally.<p>
<a name="24644"></a>
<h2>14.2    Blocks</h2>
<a name="6391"></a>
A <i>block</i> is a sequence of statements and local variable declaration statements 
within braces.
<p><ul><pre>
<i>Block:<br>
</i>	<code>{ </code><i>BlockStatements</i><sub><i>opt</i></sub><code> }
</code>
<i>BlockStatements:<br>
</i><code>	</code><i>BlockStatement<br>
</i><code>	</code><i>BlockStatements</i><code> </code><i>BlockStatement
</i>
<i>BlockStatement:<br>
</i>	<i>LocalVariableDeclarationStatement<br>
</i>	<i>Statement
</i></pre></ul><a name="5918"></a>
A block is executed by executing each of the local variable declaration statements and other statements in order from first to last (left to right). If all of these block statements complete normally, then the block completes normally. If any of these block statements complete abruptly for any reason, then the block completes abruptly for the same reason.<p>
<a name="5920"></a>
<h2>14.3    Local Variable Declaration Statements</h2>
<a name="25561"></a>
A <i>local variable declaration statement</i> declares one or more local variable names.
<p><ul><pre>
<i>LocalVariableDeclarationStatement:<br>
</i>	<i>LocalVariableDeclaration</i><code> ;
</code>
<i>LocalVariableDeclaration:<br>
</i>	<i>Type</i><code> </code><i>VariableDeclarators
</i></pre></ul><a name="238231"></a>
The following are repeated from <a href="8.doc.html#40898">&#167;8.3</a> to make the presentation here clearer:
<p><ul><pre>
<i>VariableDeclarators:<br>
</i>	<i>VariableDeclarator<br>
</i>	<i>VariableDeclarators</i><code> , </code><i>VariableDeclarator
</i>
<i>VariableDeclarator:<br>
</i>	<i>VariableDeclaratorId<br>
</i>	<i>VariableDeclaratorId</i><code> = </code><i>VariableInitializer
</i>
<i>VariableDeclaratorId:<br>
</i>	<i>Identifier<br>
</i>	<i>VariableDeclaratorId</i><code> [ ]
</code>
<i>VariableInitializer:<br>
</i>	<i>Expression<br>
</i>	<i>ArrayInitializer
</i></pre></ul><a name="32641"></a>
Every local variable declaration statement is immediately contained by a block. Local variable declaration statements may be intermixed freely with other kinds of statements in the block.<p>
<a name="35375"></a>
A local variable declaration can also appear in the header of a <code>for</code> statement <a href="14.doc.html#24588">(&#167;14.12)</a>. In this case it is executed in the same manner as if it were part of a local variable declaration statement.<p>
<a name="35393"></a>
<h3>14.3.1    Local Variable Declarators and Types</h3>
<a name="35391"></a>
Each <i>declarator</i> in a local variable declaration declares one local variable, whose 
name is the <i>Identifier</i> that appears in the declarator.
<p><a name="35396"></a>
The type of the variable is denoted by the <i>Type</i> that appears at the start of the local variable declaration, followed by any bracket pairs that follow the <i>Identifier</i> in the declarator. Thus, the local variable declaration:<p>
<pre><a name="35400"></a>int a, b[], c[][];
</pre><a name="35401"></a>
is equivalent to the series of declarations:
<p><pre><a name="35402"></a>
int a;
<a name="35403"></a>int[] b;
<a name="35404"></a>int[][] c;
</pre><a name="35405"></a>
Brackets are allowed in declarators as a nod to the tradition of C and C++. The 
general rule, however, also means that the local variable declaration:
<p><pre><a name="35406"></a>float[][] f[][], g[][][], h[];													// Yechh!
</pre><a name="35409"></a>
is equivalent to the series of declarations:
<p><pre><a name="35410"></a>
float[][][][] f;
<a name="35411"></a>float[][][][][] g;
<a name="35412"></a>float[][][] h;
</pre><a name="35427"></a>
We do not recommend such "mixed notation" for array declarations.
<p><a name="32644"></a>
<h3>14.3.2    Scope of Local Variable Declarations</h3>
<a name="45940"></a>
The scope of a local variable declared in a block is the rest of the block, including 
its own initializer. The name of the local variable parameter may not be redeclared 
as a local variable or exception parameter within its scope, or a compile-time error 
occurs; that is, hiding the name of a local variable is not permitted.
<p><a name="45944"></a>
A local variable cannot be referred to using a qualified name <a href="6.doc.html#33916">(&#167;6.6)</a>, only a simple name.<p>
<a name="45938"></a>
The example:<p>
<pre><a name="32598"></a>
class Test {
<a name="32601"></a>	static int x;
<a name="32599"></a>	public static void main(String[] args) {
<a name="32600"></a>		int x = x;
<a name="32602"></a>	}
<a name="32603"></a>}
</pre><a name="32604"></a>
causes a compile-time error because the initialization of <code>x</code> is within the scope of 
the declaration of <code>x</code> as a local variable, and the local <code>x</code> does not yet have a value 
and cannot be used.
<p><a name="32610"></a>
The following program does compile:<p>
<pre><a name="32613"></a>
class Test {
<a name="32614"></a>	static int x;
<a name="32615"></a>	public static void main(String[] args) {
<a name="32616"></a>		int x = (x=2)*2;
<a name="32619"></a>		System.out.println(x);
<a name="32617"></a>	}
<a name="32618"></a>}
</pre><a name="32611"></a>
because the local variable <code>x</code> is definitely assigned <a href="16.doc.html#25979">(&#167;16)</a> before it is used. It prints:
<p><pre><a name="236246"></a>4
</pre><a name="5925"></a>
Here is another example:<p>
<pre><a name="5926"></a>
class Test {
<a name="32622"></a>	public static void main(String[] args) {
<a name="50177"></a>		System.out.print("2+1=");
<a name="5927"></a>		int two = 2, three = two + 1;
<a name="5928"></a>		System.out.println(three);
<a name="50179"></a>	}
<a name="5929"></a>}
</pre><a name="17863"></a>
which compiles correctly and produces the output:
<p><pre><a name="17864"></a>2+1=3
</pre><a name="7616"></a>
The initializer for <code>three</code> can correctly refer to the variable <code>two</code> declared in an earlier
declarator, and the method invocation in the next line can correctly refer to the 
variable <code>three</code> declared earlier in the block.
<p><a name="35349"></a>
The scope of a local variable declared in a <code>for</code> statement is the rest of the <code>for</code> statement, including its own initializer.<p>
<a name="32558"></a>
If a declaration of an identifier as a local variable appears within the scope of a parameter or local variable of the same name, a compile-time error occurs. Thus the following example does not compile:<p>
<pre><a name="32645"></a>
class Test {
<a name="32646"></a>	public static void main(String[] args) {
<a name="50181"></a>		int i;
<a name="32663"></a>		for (int i = 0; i &lt; 10; i++)
<a name="32664"></a>			System.out.println(i);
<a name="32652"></a>	}
<a name="32653"></a>}
</pre><a name="32559"></a>
This restriction helps to detect some otherwise very obscure bugs. (A similar 
restriction on hiding of members by local variables was judged impractical, 
because the addition of a member in a superclass could cause subclasses to have to 
rename local variables.)
<p><a name="35322"></a>
On the other hand, local variables with the same name may be declared in two separate blocks or <code>for</code> statements neither of which contains the other. Thus:<p>
<pre><a name="17888"></a>
class Test {
<a name="17889"></a>	public static void main(String[] args) {
<a name="17890"></a>		for (int i = 0; i &lt; 10; i++)
<a name="17891"></a>			System.out.print(i + " ");
<a name="17892"></a>		for (int i = 10; i &gt; 0; i--)
<a name="17893"></a>			System.out.print(i + " ");
<a name="17894"></a>		System.out.println();
<a name="17895"></a>	}
<a name="17896"></a>}
</pre><a name="17897"></a>
compiles without error and, when executed, produces the output:
<p><pre><a name="17881"></a>0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
</pre><a name="32673"></a>
<h3>14.3.3    Hiding of Names by Local Variables</h3>
<a name="32716"></a>
If a name declared as a local variable is already declared as a field or type name, 
then that outer declaration is hidden throughout the scope of the local variable. 
The field or type name can almost always <a href="6.doc.html#11186">(&#167;6.8)</a> still be accessed using an appropriately
qualified name. For example, the keyword <code>this</code> can be used to access a 
hidden field <code>x</code>, using the form <code>this.x</code>. Indeed, this idiom typically appears in constructors
<a href="8.doc.html#41652">(&#167;8.6)</a>:
<p><pre><a name="32566"></a>
class Pair {
<a name="32567"></a>	Object first, second;
<a name="32568"></a>	public Pair(Object first, Object second) {
<a name="32569"></a>		this.first = first;
<a name="32570"></a>		this.second = second;
<a name="32571"></a>	}
<a name="32572"></a>}
</pre><a name="32573"></a>
In this example, the constructor takes parameters having the same names as the 
fields to be initialized. This is simpler than having to invent different names for 
the parameters and is not too confusing in this stylized context. In general, however,
it is considered poor style to have local variables with the same names as 
fields.
<p><a name="32717"></a>
<h3>14.3.4    Execution of Local Variable Declarations</h3>
<a name="32574"></a>
A local variable declaration statement is an executable statement. Every time it is 
executed, the declarators are processed in order from left to right. If a declarator 
has an initialization expression, the expression is evaluated and its value is 
assigned to the variable. If a declarator does not have an initialization expression, 
then a Java compiler must prove, using exactly the algorithm given in <a href="16.doc.html#25979">&#167;16</a>, that 
every reference to the variable is necessarily preceded by execution of an assignment
to the variable. If this is not the case, then a compile-time error occurs.
<p><a name="32578"></a>
Each initialization (except the first) is executed only if the evaluation of the preceding initialization expression completes normally. Execution of the local variable declaration completes normally only if evaluation of the last initialization expression completes normally; if the local variable declaration contains no initialization expressions, then executing it always completes normally.<p>
<a name="32584"></a>
<h2>14.4    Statements</h2>
<a name="32588"></a>
There are many kinds of statements in the Java language. Most correspond to 
statements in the C and C++ languages, but some are unique to Java.
<p><a name="5958"></a>
As in C and C++, the Java <code>if</code> statement suffers from the so-called "dangling <code>else</code> problem," illustrated by this misleadingly formatted example:<p>
<pre><a name="17933"></a>
if (door.isOpen())
<a name="5960"></a>	if (resident.isVisible())
<a name="35428"></a>		resident.greet("Hello!");
<a name="5961"></a>else door.bell.ring();								// A "dangling else"
</pre><a name="5962"></a>
The problem is that both the outer <code>if</code> statement and the inner <code>if</code> statement might 
conceivably own the <code>else</code> clause. In this example, one might surmise that the programmer
intended the <code>else</code> clause to belong to the outer <code>if</code> statement. The Java 
language, like C and C++ and many languages before them, arbitrarily decree that 
an <code>else</code> clause belongs to the innermost <code>if</code> to which it might possibly belong. 
This rule is captured by the following grammar:
<p><ul><pre>
<i>Statement:<br>
	StatementWithoutTrailingSubstatement<br>
	LabeledStatement<br>
	IfThenStatement<br>
	IfThenElseStatement<br>
	WhileStatement<br>
	ForStatement
</i>
<i>StatementNoShortIf:<br>
	StatementWithoutTrailingSubstatement<br>
	LabeledStatementNoShortIf<br>
	IfThenElseStatementNoShortIf<br>
	WhileStatementNoShortIf<br>
	ForStatementNoShortIf
</i>
<i>StatementWithoutTrailingSubstatement:<br>
	Block<br>
	EmptyStatement<br>
	ExpressionStatement<br>
	SwitchStatement<br>
	DoStatement<br>
	BreakStatement<br>
	ContinueStatement<br>
	ReturnStatement<br>
	SynchronizedStatement<br>
	ThrowStatement<br>
	TryStatement
</i></pre></ul><a name="8344"></a>
The following are repeated from <a href="14.doc.html#5991">&#167;14.8</a> to make the presentation here clearer:
<p><ul><pre>
<i>IfThenStatement:<br>
</i>	<code>if ( </code><i>Expression</i><code> ) </code><i>Statement
</i>
<i>IfThenElseStatement:<br>
</i>	<code>if ( </code><i>Expression</i><code> ) </code><i>StatementNoShortIf</i><code> else </code><i>Statement
</i>
<i>IfThenElseStatementNoShortIf:<br>
</i>	<code>if ( </code><i>Expression</i><code> ) </code><i>StatementNoShortIf</i><code> else </code><i>StatementNoShortIf
</i></pre></ul><a name="5969"></a>
Statements are thus grammatically divided into two categories: those that might end in an <code>if</code> statement that has no <code>else</code> clause (a "short <code>if</code> statement") and those that definitely do not. Only statements that definitely do not end in a short <code>if</code> statement may appear as an immediate substatement before the keyword <code>else</code> in an <code>if</code> statement that does have an <code>else</code> clause. This simple rule prevents the "dangling <code>else</code>" problem. The execution behavior of a statement with the "no short <code>if</code>" restriction is identical to the execution behavior of the same kind of statement without the "no short <code>if</code>" restriction; the distinction is drawn purely to resolve the syntactic difficulty.<p>
<a name="5970"></a>
<h2>14.5    The Empty Statement</h2>
<a name="5971"></a>
An <i>empty statement</i> does nothing.
<p><ul><pre>
<i>EmptyStatement:<br>
</i>	<code>;
</code></pre></ul><a name="5973"></a>
Execution of an empty statement always completes normally.
<p><a name="78993"></a>
<h2>14.6    Labeled Statements</h2>
<a name="78994"></a>
Statements may have <i>label</i> prefixes.
<p><ul><pre>
<i>LabeledStatement:<br>
</i>	<i>Identifier</i><code> : </code><i>Statement
</i>
<i>LabeledStatementNoShortIf:<br>
</i>	<i>Identifier</i><code> : </code><i>StatementNoShortIf
</i></pre></ul><a name="78997"></a>
The <i>Identifier</i> is declared to be the label of the immediately contained <i>Statement</i>.
<p><a name="17941"></a>
Unlike C and C++, the Java language has no <code>goto</code> statement; identifier statement labels are used with <code>break</code> <a href="14.doc.html#6842">(&#167;14.13)</a> or <code>continue</code> <a href="14.doc.html#6122">(&#167;14.14)</a> statements appearing anywhere within the labeled statement.<p>
<a name="78998"></a>
A statement labeled by an identifier must not appear anywhere within another statement labeled by the same identifier, or a compile-time error will occur. Two statements can be labeled by the same identifier only if neither statement contains the other.<p>
<a name="35441"></a>
There is no restriction against using the same identifier as a label and as the name of a package, class, interface, method, field, parameter, or local variable. Use of an identifier to label a statement does not hide a package, class, interface, method, field, parameter, or local variable with the same name. Use of an identifier &#32;as a local variable or as the parameter of an exception handler <a href="14.doc.html#79311">(&#167;14.18)</a> does not hide a statement label with the same name.<p>
<a name="79000"></a>
A labeled statement is executed by executing the immediately contained <i>Statement</i>. If the statement is labeled by an <i>Identifier</i> and the contained <i>Statement</i> completes abruptly because of a <code>break</code> with the same <i>Identifier</i>, then the labeled statement completes normally. In all other cases of abrupt completion of the <i>Statement</i>, &#32;the labeled statement completes abruptly for the same reason.<p>
<a name="5984"></a>
<h2>14.7    Expression Statements</h2>
<a name="5985"></a>
Certain kinds of expressions may be used as statements by following them with 
semicolons:
<p><ul><pre>
<i>ExpressionStatement:<br>
</i>	<i>StatementExpression</i><code> ;
</code>
<i>StatementExpression:<br>
</i>	<i>Assignment<br>
	PreIncrementExpression<br>
	PreDecrementExpression<br>
	PostIncrementExpression<br>
	PostDecrementExpression<br>
	MethodInvocation<br>
</i>	<i>ClassInstanceCreationExpression
</i></pre></ul><a name="5988"></a>
An <i>expression statement</i> is executed by evaluating the expression; if the expression has a value, the value is discarded. Execution of the expression statement completes normally if and only if evaluation of the expression completes normally.<p>
<a name="5989"></a>
Unlike C and C++, the Java language allows only certain forms of expressions to be used as expression statements. Note that Java does not allow a "cast to <code>void</code>"-<code>void</code> is not a type in Java-so the traditional C trick of writing an expression statement such as:<p>
<pre><a name="35455"></a>(void) ... ;								// This idiom belongs to C, not to Java!
</pre><a name="35457"></a>
does not work in Java. On the other hand, Java allows all the most useful kinds of 
expressions in expressions statements, and Java does not require a method invocation
used as an expression statement to invoke a <code>void</code> method, so such a trick is 
almost never needed. If a trick is needed, either an assignment statement <a href="15.doc.html#5281">(&#167;15.25)</a> 
or a local variable declaration statement <a href="14.doc.html#5920">(&#167;14.3)</a> can be used instead.
<p><a name="5991"></a>
<h2>14.8    The <code>if</code> Statement</h2>
<a name="35469"></a>
The <code>if</code> statement allows conditional execution of a statement or a conditional 
choice of two statements, executing one or the other but not both.
<p><ul><pre>
<i>IfThenStatement:<br>
</i>	<code>if ( </code><i>Expression</i><code> ) </code><i>Statement
</i>
<i>IfThenElseStatement:<br>
</i>	<code>if ( </code><i>Expression</i><code> ) </code><i>StatementNoShortIf</i><code> else </code><i>Statement
</i>
<i>IfThenElseStatementNoShortIf:<br>
</i>	<code>if ( </code><i>Expression</i><code> ) </code><i>StatementNoShortIf</i><code> else </code><i>StatementNoShortIf
</i></pre></ul><a name="24313"></a>
The <i>Expression</i> must have type <code>boolean</code>, or a compile-time error occurs.
<p><a name="237433"></a>
<h3>14.8.1    The <code>if-then</code> Statement</h3>
<a name="35473"></a>
An <code>if</code>-<code>then</code> statement is executed by first evaluating the <i>Expression</i>. If evaluation 
of the <i>Expression</i> completes abruptly for some reason, the <code>if</code>-<code>then</code> statement 
completes abruptly for the same reason. Otherwise, execution continues by making
a choice based on the resulting value:
<p><ul><a name="5997"></a>
<li>If the value is <code>true</code>, then the contained <i>Statement</i> is executed; the <code>if</code>-<code>then</code> statement completes normally only if execution of the <i>Statement</i> completes normally.
<a name="5998"></a>
<li>If the value is <code>false</code>, no further action is taken and the <code>if</code>-<code>then</code> statement completes normally.
</ul><a name="237435"></a>
<h3>14.8.2    The <code>if-then-else</code> Statement</h3>
<a name="236506"></a>
An <code>if</code>-<code>then</code>-<code>else</code> statement is executed by first evaluating the <i>Expression</i>. If 
evaluation of the <i>Expression</i> completes abruptly for some reason, then the <code>if</code>-
<code>then</code>-<code>else</code> &#32;statement completes abruptly for the same reason. Otherwise, execution
continues by making a choice based on the resulting value:
<p><ul><a name="6000"></a>
<li>If the value is <code>true</code>, then the first contained <i>Statement</i> (the one before the <code>else</code> keyword) is executed; the <code>if</code>-<code>then</code>-<code>else</code> statement completes normally only if execution of that statement completes normally.
<a name="42708"></a>
<li>If the value is <code>false</code>, then the second contained <i>Statement</i> (the one after the <code>else</code> keyword) is executed; the <code>if</code>-<code>then</code>-<code>else</code> statement completes normally only if execution of that statement completes normally. 
</ul><a name="35518"></a>
<h2>14.9    The <code>switch</code> Statement</h2>
<a name="35522"></a>
The <code>switch</code> statement transfers control to one of several statements depending on 
the value of an expression.
<p><ul><pre>
<i>SwitchStatement:<br>
</i><code>	switch ( </code><i>Expression</i><code> ) </code><i>SwitchBlock
</i>
<i>SwitchBlock:<br>
</i>	<code>{ </code>S<i>witchBlockStatementGroups</i><sub><i>opt</i></sub><code> </code><i>SwitchLabels</i><sub><i>opt</i></sub><code> }
</code>
<i>SwitchBlockStatementGroups:<br>
</i><code>	</code><i>SwitchBlockStatementGroup<br>
</i><code>	</code><i>SwitchBlockStatementGroups</i><code> </code><i>SwitchBlockStatementGroup
</i>
<i>SwitchBlockStatementGroup:<br>
</i>	<i>SwitchLabels</i><code> </code><i>BlockStatements
</i>
<i>SwitchLabels:<br>
</i>	<i>SwitchLabel<br>
</i>	<i>SwitchLabels</i><code> </code><i>SwitchLabel
</i>
<i>SwitchLabel:<br>
</i><code>	case </code><i>ConstantExpression</i><code> :<br>
	default :
</code></pre></ul><a name="237298"></a>
The type of the <i>Expression</i> must be <code>char</code>, <code>byte</code>, <code>short</code>, or <code>int</code>, or a compile-time error occurs.<p>
<a name="237299"></a>
The body of a <code>switch</code> statement must be a block. Any statement immediately contained by the block may be labeled with one or more <code>case</code> or <code>default</code> labels. These labels are said to be <i>associated</i> with the <code>switch</code> statement, as are the values of the constant expressions <a href="15.doc.html#5313">(&#167;15.27)</a> in the <code>case</code> labels.<p>
<a name="237328"></a>
All of the following must be true, or a compile-time error will result:<p>
<ul><a name="237329"></a>
<li>Every <code>case</code> constant expression associated with a <code>switch</code> statement must be assignable <a href="5.doc.html#170768">(&#167;5.2)</a> to the type of the <code>switch</code> <i>Expression</i>.
<a name="237333"></a>
<li>No two of the <code>case</code> constant expressions associated with a <code>switch</code> statement may have the same value.
<a name="237334"></a>
<li>At most one <code>default</code> label may be associated with the same <code>switch</code> statement.
</ul><a name="237303"></a>
In C and C++ the body of a <code>switch</code> statement can be a statement and statements with <code>case</code> labels do not have to be immediately contained by that statement. Consider the simple loop:<p>
<pre><a name="237281"></a>for (i = 0; i &lt; n; ++i) foo();
</pre><a name="237282"></a>
where <code>n</code> is known to be positive. A trick known as <i>Duff's device</i> can be used in C 
or C++ to unroll the loop, but this is not valid Java code:
<p><pre><a name="237283"></a>
int q = (n+7)/8;
<a name="237284"></a>switch (n%8) {
<a name="237285"></a>case 0:			do {		foo();				// Great C hack, Tom,
<a name="237286"></a>case 7:					foo();				// but it's not valid in Java.
<a name="237287"></a>case 6:					foo();
<a name="237288"></a>case 5:					foo();
<a name="237289"></a>case 4:					foo();
<a name="237290"></a>case 3:					foo();
<a name="237291"></a>case 2:					foo();
<a name="237292"></a>case 1:					foo();
<a name="237293"></a>			} while (--q &gt;= 0);
<a name="237294"></a>}
</pre><a name="237295"></a>
Fortunately, this trick does not seem to be widely known or used. Moreover, it is 
less needed nowadays; this sort of code transformation is properly in the province 
of state-of-the-art optimizing compilers.
<p><a name="217138"></a>
When the <code>switch</code> statement is executed, first the <i>Expression</i> is evaluated. If evaluation of the <i>Expression</i> completes abruptly for some reason, the <code>switch</code> statement completes abruptly for the same reason. Otherwise, execution continues by comparing the value of the <i>Expression </i>with each <code>case</code> constant. Then there is a choice:<p>
<ul><a name="6012"></a>
<li>If one of the <code>case</code> constants is equal to the value of the expression, then we say that the <code>case</code> matches, and all statements after the matching <code>case</code> label in the switch block, if any, are executed in sequence. If all these statements complete normally, or if there are no statements after the matching <code>case</code> label, then the entire <code>switch</code> statement completes normally.
</ul><ul><a name="6013"></a>
<li>If no <code>case</code> matches but there is a <code>default</code> label, then all statements after the matching <code>default</code> label in the switch block, if any, are executed in sequence. If all these statements complete normally, or if there are no statements after the <code>default</code> label, then the entire <code>switch</code> statement completes normally.
<a name="6014"></a>
<li>If no <code>case</code> matches and there is no <code>default</code> label, then no further action is taken and the <code>switch</code> statement completes normally.
</ul><a name="237254"></a>
If any statement immediately contained by the <i>Block</i> body of the <code>switch</code> statement completes abruptly, it is handled as follows:<p>
<ul><a name="6017"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>break</code> with no label, no further action is taken and the <code>switch</code> statement completes normally.
<a name="237272"></a>
<li>If execution of the <i>Statement</i> completes abruptly for any other reason, the <code>switch</code> statement completes abruptly for the same reason. The case of abrupt completion because of a <code>break</code> with a label is handled by the general rule for labeled statements <a href="14.doc.html#78993">(&#167;14.6)</a>.
</ul><a name="237607"></a>
As in C and C++, execution of statements in a switch block "falls through labels" in Java. For example, the program:<p>
<pre><a name="237615"></a>
class Toomany {
<a name="237616"></a>
	static void howMany(int k) {
<a name="237617"></a>		switch (k) {
<a name="237618"></a>		case 1:			System.out.print("one ");
<a name="237619"></a>		case 2:			System.out.print("too ");
<a name="237620"></a>		case 3:			System.out.println("many");
<a name="237621"></a>		}
<a name="237622"></a>	}
<br><a name="237623"></a>
	public static void main(String[] args) {
<a name="237624"></a>		howMany(3);
<a name="237625"></a>		howMany(2);
<a name="237626"></a>		howMany(1);
<a name="237627"></a>	}
<br><a name="237628"></a>}
</pre><a name="237629"></a>
contains a switch block in which the code for each case falls through into the code 
for the next case. As a result, the program prints:
<p><pre><a name="237632"></a>
many
<a name="237633"></a>too many
<a name="237634"></a>one too many
</pre><a name="237630"></a>
If code is not to fall through case to case in this manner, then <code>break</code> statements 
should be used, as in this example:
<p><pre><a name="237644"></a>
class Twomany {
<a name="237645"></a>
	static void howMany(int k) {
<a name="237646"></a>		switch (k) {
<a name="237647"></a>		case 1:			System.out.println("one");
<a name="237648"></a>					break;					// exit the switch
<a name="237649"></a>		case 2:			System.out.println("two");
<a name="237650"></a>					break;					// exit the switch
<a name="237651"></a>		case 3:			System.out.println("many");
<a name="237652"></a>					break;					// not needed, but good style
<a name="237653"></a>		}
<a name="237654"></a>	}
<br><a name="237655"></a>
	public static void main(String[] args) {
<a name="237656"></a>		howMany(1);
<a name="237657"></a>		howMany(2);
<a name="237658"></a>		howMany(3);
<a name="237659"></a>	}
<br><a name="237660"></a>}
</pre><a name="237642"></a>
This program prints:
<p><pre><a name="237670"></a>
one
<a name="237671"></a>two
<a name="237672"></a>many
</pre><a name="237277"></a>
<h2>14.10    The <code>while</code> Statement</h2>
<a name="237278"></a>
The <code>while</code> statement executes an <i>Expression</i> and a <i>Statement</i> repeatedly until the 
value of the <i>Expression</i> is <code>false</code>.
<p><ul><pre>
<i>WhileStatement:<br>
</i>	<code>while ( </code><i>Expression</i><code> ) </code><i>Statement
</i>
<i>WhileStatementNoShortIf:<br>
</i>	<code>while ( </code><i>Expression</i><code> ) </code><i>StatementNoShortIf
</i></pre></ul><a name="35485"></a>
The <i>Expression</i> must have type <code>boolean</code>, or a compile-time error occurs.
<p><a name="217153"></a>
A <code>while</code> statement is executed by first evaluating the <i>Expression</i>. If evaluation of the <i>Expression</i> completes abruptly for some reason, the <code>while</code> statement completes abruptly for the same reason. Otherwise, execution continues by making a choice based on the resulting value:<p>
<ul><a name="6028"></a>
<li>If the value is <code>true</code>, then the contained <i>Statement</i> is executed. Then there is a choice:
<ul>
<a name="6029"></a>
<li>If execution of the <i>Statement</i> completes normally, then the entire <code>while</code> statement is executed again, beginning by re-evaluating the <i>Expression</i>.
<a name="6030"></a>
<li>If execution of the <i>Statement</i> completes abruptly, see <a href="14.doc.html#21139">&#167;14.10.1</a> below.
</ul>
<a name="6031"></a>
<li>If the value of the <i>Expression</i> is <code>false</code>, no further action is taken and the <code>while</code> statement completes normally.
</ul><a name="6032"></a>
If the value of the <i>Expression</i> is <code>false</code> the first time it is evaluated, then the 
<i>Statement</i> &#32;is not executed.
<p><a name="21139"></a>
<h3>14.10.1    Abrupt Completion</h3>
<a name="6033"></a>
Abrupt completion of the contained <i>Statement</i> is handled in the following manner:
<p><ul><a name="6034"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>break</code> with no label, no further action is taken and the <code>while</code> statement completes normally.
<ul>
<a name="6035"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>continue</code> with no label, then the entire <code>while</code> statement is executed again.
<a name="79063"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>continue</code> with label <i>L</i>, then there is a choice:
<ul>
<a name="79064"></a>
<li>If the <code>while</code> statement has label <i>L</i>, then the entire <code>while</code> statement is executed again.
<a name="79065"></a>
<li>If the <code>while</code> statement does not have label <i>L</i>, the <code>while</code> statement completes abruptly because of a <code>continue</code> with label <i>L</i>.
</ul>
<a name="79070"></a>
<li>If execution of the <i>Statement</i> completes abruptly for any other reason, the <code>while</code> statement completes abruptly for the same reason. Note that the case of abrupt completion because of a <code>break</code> with a label is handled by the general rule for labeled statements <a href="14.doc.html#78993">(&#167;14.6)</a>.
</ul>
</ul><a name="6045"></a>
<h2>14.11    The <code>do</code> Statement</h2>
<a name="35504"></a>
The <code>do</code> statement executes a <i>Statement</i> and an <i>Expression</i> repeatedly until the 
value of the <i>Expression</i> is <code>false</code>.
<p><ul><pre>
<i>DoStatement:<br>
</i><code>	do </code><i>Statement</i><code> while ( </code><i>Expression</i><code> ) ;
</code></pre></ul><a name="35496"></a>
The <i>Expression</i> must have type <code>boolean</code>, or a compile-time error occurs.
<p><a name="6048"></a>
A <code>do</code> statement is executed by first executing the <i>Statement</i>. Then there is a choice:<p>
<ul><a name="217176"></a>
<li>If execution of the <i>Statement</i> completes normally, then the <i>Expression</i> is evaluated. If evaluation of the <i>Expression</i> completes abruptly for some reason, the <code>do</code> statement completes abruptly for the same reason. Otherwise, there is a choice based on the resulting value:
<ul>
<a name="217172"></a>
<li>If the value is <code>true</code>, then the entire <code>do</code> statement is executed again.
<a name="6051"></a>
<li>If the value is <code>false</code>, no further action is taken and the <code>do</code> statement completes normally.
</ul>
<a name="6052"></a>
<li>If execution of the <i>Statement</i> completes abruptly, see <a href="14.doc.html#45366">&#167;14.11.1</a> below.
</ul><a name="6053"></a>
Executing a <code>do</code> statement always executes the contained <i>Statement</i> at least once.
<p><a name="45366"></a>
<h3>14.11.1    Abrupt Completion</h3>
<a name="43246"></a>
Abrupt completion of the contained <i>Statement</i> is handled in the following manner:
<p><ul><a name="6714"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>break</code> with no label, then no further action is taken and the <code>do</code> statement completes normally.
<a name="6056"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>continue</code> with no label, then the <i>Expression</i> is evaluated. Then there is a choice based on the resulting value:
<ul>
<a name="6057"></a>
<li>If the value is <code>true</code>, then the entire <code>do</code> statement is executed again.
<a name="6058"></a>
<li>If the value is <code>false</code>, no further action is taken and the <code>do</code> statement completes normally.
</ul>
<a name="79109"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>continue</code> with label <i>L</i>, then there is a choice:
<ul>
<a name="79110"></a>
<li>If the <code>do</code> statement has label <i>L</i>, then the <i>Expression</i> is evaluated. Then there is a choice:
<ul>
<a name="79111"></a>
<li>If the value of the <i>Expression</i> is <code>true</code>, then the entire <code>do</code> statement is executed again.
<a name="79112"></a>
<li>If the value of the <i>Expression</i> is <code>false</code>, no further action is taken and the <code>do</code> statement completes normally.
</ul>
<a name="79113"></a>
<li>If the <code>do</code> statement does not have label <i>L</i>, the <code>do</code> statement completes abruptly because of a <code>continue</code> with label <i>L</i>.
</ul>
<a name="24581"></a>
<li>If execution of the <i>Statement</i> completes abruptly for any other reason, the <code>do</code> statement completes abruptly for the same reason. The case of abrupt completion because of a <code>break</code> with a label is handled by the general rule <a href="14.doc.html#78993">(&#167;14.6)</a>.
</ul><a name="24585"></a>
<h3>14.11.2    Example of <code>do</code> statement</h3>
<a name="43313"></a>
The following code is one possible implementation of the <code>toHexString</code> method 
<a href="javalang.doc6.html#7332">(&#167;20.7.14)</a> of class <code>Integer</code>:
<p><pre><a name="43303"></a>
public static String toHexString(int i) {
<a name="43304"></a>	StringBuffer buf = new StringBuffer(8);
<a name="43305"></a>	do {
<a name="43306"></a>		buf.append(Character.forDigit(i &amp; 0xF, 16));
<a name="43307"></a>		i &gt;&gt;&gt;= 4;
<a name="43308"></a>	} while (i != 0);
<a name="43309"></a>	return buf.reverse().toString();
<a name="43310"></a>}
</pre><a name="24586"></a>
Because at least one digit must be generated, the <code>do</code> statement is an appropriate 
control structure.
<p><a name="24588"></a>
<h2>14.12    The <code>for</code> Statement</h2>
<a name="35537"></a>
The <code>for</code> statement executes some initialization code, then executes an <i>Expression</i>, 
a <i>Statement</i>, and some update code repeatedly until the value of the <i>Expression</i> is 
<code>false</code>.
<p><ul><pre>
<i>ForStatement:<br>
</i>	<code>for ( </code><i>ForInit</i><sub><i>opt</i></sub><code> ; </code><i>Expression</i><sub><i>opt</i></sub><code> ; </code><i>ForUpdate</i><sub><i>opt</i></sub><code> )<br>
</code>		<i>Statement
</i>
<i>ForStatementNoShortIf:<br>
</i>	<code>for ( </code><i>ForInit</i><sub><i>opt</i></sub><code> ; </code><i>Expression</i><sub><i>opt</i></sub><code> ; </code><i>ForUpdate</i><sub><i>opt</i></sub><code> )<br>
		</code><i>StatementNoShortIf
</i>
<i>ForInit:<br>
</i>	<i>StatementExpressionList<br>
	LocalVariableDeclaration
</i>
<i>ForUpdate:<br>
	StatementExpressionList
</i>
<i>StatementExpressionList:<br>
	StatementExpression<br>
	StatementExpressionList</i><code> , </code><i>StatementExpression
</i></pre></ul><a name="35529"></a>
The <i>Expression</i> must have type <code>boolean</code>, or a compile-time error occurs.
<p><a name="45367"></a>
<h3>14.12.1    Initialization of <code>for</code> statement</h3>
<a name="11751"></a>
A <code>for</code> statement is executed by first executing the <i>ForInit</i> code:
<p><ul><a name="6081"></a>
<li>If the <i>ForInit</i> code is a list of statement expressions <a href="14.doc.html#5984">(&#167;14.7)</a>, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the <code>for</code> statement completes abruptly for the same reason; any <i>ForInit</i> statement expressions to the right of the one that completed abruptly are not evaluated.
<a name="6082"></a>
<li>If the <i>ForInit</i> code is a local variable declaration, it is executed as if it were a local variable declaration statement <a href="14.doc.html#5920">(&#167;14.3)</a> appearing in a block. In this case, the scope of a declared local variable is its own initializer and any further declarators in the <i>ForInit</i> part, plus the <i>Expression</i>, <i>ForUpdate</i>, and contained <i>Statement</i> of the <code>for</code> statement. If execution of the local variable declaration completes abruptly for any reason, the <code>for</code> statement completes abruptly for the same reason.
<a name="6083"></a>
<li>If the <i>ForInit</i> part is not present, no action is taken.
</ul><a name="45370"></a>
<h3>14.12.2    Iteration of <code>for</code> statement</h3>
<a name="217196"></a>
Next, a <code>for</code> iteration step is performed, as follows:
<p><ul><a name="217202"></a>
<li>If the <i>Expression</i> is present, it is evaluated, and if evaluation of the <i>Expression</i> completes abruptly, the <code>for</code> statement completes abruptly for the same reason. Otherwise, there is then a choice based on the presence or absence of the <i>Expression</i> and the resulting value if the <i>Expression</i> is present:
<ul>
<a name="6086"></a>
<li>If the <i>Expression</i> is not present, or it is present and the value resulting from its evaluation is <code>true</code>, then the contained <i>Statement</i> is executed. Then there is a choice:
<ul>
<a name="6087"></a>
<li>If execution of the <i>Statement</i> completes normally, then the following two steps are performed in sequence:
<ul>
<a name="45351"></a>
<li>First, if the <i>ForUpdate</i> part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If evaluation of any expression completes abruptly for some reason, the <code>for</code> statement completes abruptly for the same reason; any <i>ForUpdate</i> statement expressions to the right of the one that completed abruptly are not evaluated. If the <i>ForUpdate</i> part is not present, no action is taken.
<a name="236152"></a>
<li>Second, another <code>for</code> iteration step is performed.
</ul>
<a name="236156"></a>
<li>If execution of the <i>Statement</i> completes abruptly, see <a href="14.doc.html#45371">&#167;14.12.3</a> below.
</ul>
<a name="236157"></a>
<li>If the <i>Expression</i> is present and the value resulting from its evaluation is <code>false</code>, no further action is taken and the <code>for</code> statement completes normally.
</ul>
</ul><a name="6092"></a>
If the value of the <i>Expression</i> is <code>false</code> the first time it is evaluated, then the <i>Statement</i> is not executed.<p>
<a name="6093"></a>
If the <i>Expression</i> is not present, then the only way a <code>for</code> statement can complete normally is by use of a <code>break</code> statement.<p>
<a name="45371"></a>
<h3>14.12.3    Abrupt Completion of <code>for</code> statement</h3>
<a name="43248"></a>
Abrupt completion of the contained <i>Statement</i> is handled in the following manner:
<p><ul><a name="6095"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>break</code> with no label, no further action is taken and the <code>for</code> statement completes normally.
<a name="6096"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>continue</code> with no label, then the following two steps are performed in sequence:
<ul>
<a name="6097"></a>
<li>First, if the <i>ForUpdate</i> part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the <i>ForUpdate</i> &#32;part is not present, no action is taken.
<a name="6098"></a>
<li>Second, another <code>for</code> iteration step is performed.
</ul>
<a name="79161"></a>
<li>If execution of the <i>Statement</i> completes abruptly because of a <code>continue</code> with label <i>L</i>, then there is a choice:
<ul>
<a name="79162"></a>
<li>If the <code>for</code> statement has label <i>L</i>, then the following two steps are performed in sequence:
<ul>
<a name="79163"></a>
<li>First, if the <i>ForUpdate</i> part is present, the expressions are evaluated in sequence from left to right; their values, if any, are discarded. If the<i> ForUpdate</i> is not present, no action is taken.
<a name="79164"></a>
<li>Second, another <code>for</code> iteration step is performed.
</ul>
<a name="79165"></a>
<li>If the <code>for</code> statement does not have label <i>L</i>, the <code>for</code> statement completes abruptly because of a <code>continue</code> with label <i>L</i>.
</ul>
<a name="6104"></a>
<li>If execution of the <i>Statement</i> completes abruptly for any other reason, the <code>for</code> statement completes abruptly for the same reason. Note that the case of abrupt completion because of a <code>break</code> with a label is handled by the general rule for labeled statements <a href="14.doc.html#78993">(&#167;14.6)</a>.
</ul><a name="6842"></a>
<h2>14.13    The <code>break</code> Statement</h2>
<a name="35540"></a>
A break statement transfers control out of an enclosing statement.
<p><ul><pre>
<i>BreakStatement:<br>
</i>	<code>break </code><i>Identifier</i><sub><i>opt</i></sub><code> ;
</code></pre></ul><a name="43392"></a>
A <code>break</code> statement with no label attempts to transfer control to the innermost enclosing <code>switch</code>, <code>while</code>, <code>do</code>, or <code>for</code> statement; this statement, which is called the <i>break target</i>, then immediately completes normally. To be precise, a <code>break</code> statement with no label always completes abruptly, the reason being a <code>break</code> with no label. If no <code>switch</code>, <code>while</code>, <code>do</code>, or <code>for</code> statement encloses the <code>break</code> statement, a compile-time error occurs.<p>
<a name="79188"></a>
A <code>break</code> statement with label <i>Identifier</i> attempts to transfer control to the enclosing labeled statement <a href="14.doc.html#78993">(&#167;14.6)</a> that has the same <i>Identifier</i> as its label; this statement, which is called the <i>break target</i>, then immediately completes normally. In this case, the <code>break</code> target need not be a <code>while</code>, <code>do</code>, <code>for</code>, or <code>switch</code> statement. To be precise, a <code>break</code> statement with label <i>Identifier</i> always completes abruptly, the reason being a <code>break</code> with label <i>Identifier</i>. If no labeled statement with <i>Identifier</i> &#32;as its label encloses the <code>break</code> statement, a compile-time error occurs.<p>
<a name="43504"></a>
It can be seen, then, that a <code>break</code> statement always completes abruptly.<p>
<a name="43404"></a>
The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any <code>try</code> statements <a href="14.doc.html#79311">(&#167;14.18)</a> within the break target whose <code>try</code> blocks contain the <code>break</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements are executed, in order, innermost to outermost, before control is transferred to the break target. Abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>break</code> statement.<p>
<a name="18004"></a>
In the following example, a mathematical graph is represented by an array of arrays. A graph consists of a set of nodes and a set of edges; each edge is an arrow that points from some node to some other node, or from a node to itself. In this example it is assumed that there are no redundant edges; that is, for any two nodes <i>P</i> and <i>Q</i>, where <i>Q</i> may be the same as <i>P</i>, there is at most one edge from <i>P</i> to <i>Q</i>. Nodes are represented by integers, and there is an edge from node <i>i</i> to node <code>edges[</code><i>i</i><code>][</code><i>j</i><code>]</code> for every <i>i</i> and <i>j</i> for which the array reference <code>edges[</code><i>i</i><code>][</code><i>j</i><code>]</code> does not throw an <code>IndexOutOfBoundsException</code>.<p>
<a name="42801"></a>
The task of the method <code>loseEdges</code>, given integers <i>i</i> and <i>j</i>, is to construct a new graph by copying a given graph but omitting the edge from node <i>i</i> to node <i>j</i>, if any, and the edge from node <i>j</i> to node <i>i</i>, if any:<p>
<pre><a name="42813"></a>
class Graph {
<a name="42814"></a>	int edges[][];
<a name="42816"></a>	public Graph(int[][] edges) { this.edges = edges; }
<a name="42818"></a>
	public Graph loseEdges(int i, int j) {
<a name="42819"></a>		int n = edges.length;
<a name="42820"></a>		int[][] newedges = new int[n][];
<a name="42821"></a>		for (int k = 0; k &lt; n; ++k) {
<a name="42822"></a>
			edgelist: {
<a name="42823"></a>				int z;
<a name="42824"></a>
				search: {
<a name="42825"></a>					if (k == i) {
<a name="42826"></a>						for (z = 0; z &lt; edges[k].length; ++z)
<a name="42827"></a>							if (edges[k][z] == j)
<a name="42828"></a>								break search;
<a name="42829"></a>					} else if (k == j) {
<a name="42831"></a>						for (z = 0; z &lt; edges[k].length; ++z)
<a name="42832"></a>							if (edges[k][z] == i)
<a name="42833"></a>								break search;
<a name="42834"></a>					}
<a name="42835"></a>					// No edge to be deleted; share this list.
<a name="42836"></a>					newedges[k] = edges[k];
<a name="42837"></a>					break edgelist;
<a name="42838"></a>				}//search
<a name="42839"></a>				// Copy the list, omitting the edge at position z.
<a name="42840"></a>				int m = edges[k].length - 1;
<a name="42841"></a>				int ne[] = new int[m];
<a name="42842"></a>				System.arraycopy(edges[k], 0, ne, 0, z);
<a name="42843"></a>				System.arraycopy(edges[k], z+1, ne, z, m-z);
<a name="42879"></a>				newedges[k] = ne;
<a name="42844"></a>			}//edgelist
<a name="42845"></a>		}
<a name="42846"></a>		return new Graph(newedges);
<a name="42847"></a>	}
<a name="42848"></a>}
</pre><a name="42887"></a>
Note the use of two statement labels, <code>edgelist</code> and <code>search</code>, and the use of <code>break</code> 
statements. This allows the code that copies a list, omitting one edge, to be shared 
between two separate tests, the test for an edge from node <i>i</i> to node <i>j</i>, and the test 
for an edge from node <i>j</i> to node <i>i</i>.
<p><a name="6122"></a>
<h2>14.14    The <code>continue</code> Statement</h2>
<a name="6123"></a>
A <code>continue</code> statement may occur only in a <code>while</code>, <code>do</code>, or <code>for</code> statement; statements
of these three kinds are called <i>iteration statements</i>. Control passes to the 
loop-continuation point of an iteration statement.
<p><ul><pre>
<i>ContinueStatement:<br>
</i>	<code>continue </code><i>Identifier</i><sub><i>opt</i></sub><code> ;
</code></pre></ul><a name="6125"></a>
A <code>continue</code> statement with no label attempts to transfer control to the innermost enclosing <code>while</code>, <code>do</code>, or <code>for</code> statement; this statement, which is called the <i>continue target</i>, then immediately ends the current iteration and begins a new one. To be precise, such a <code>continue</code> statement always completes abruptly, the reason being a <code>continue</code> with no label. If no <code>while</code>, <code>do</code>, or <code>for</code> statement encloses the <code>continue</code> statement, a compile-time error occurs.<p>
<a name="79215"></a>
A <code>continue</code> statement with label <i>Identifier</i> attempts to transfer control to the enclosing labeled statement <a href="14.doc.html#78993">(&#167;14.6)</a> that has the same <i>Identifier</i> as its label; that statement, which is called the <i>continue target</i>, then immediately ends the current iteration and begins a new one. The continue target must be a <code>while</code>, <code>do</code>, or <code>for</code> statement or a compile-time error occurs. More precisely, a <code>continue</code> statement with label <i>Identifier</i> always completes abruptly, the reason being a <code>continue</code> with label <i>Identifier</i>. If no labeled statement with <i>Identifier</i> as its label contains the <code>continue</code> statement, a compile-time error occurs.<p>
<a name="43498"></a>
It can be seen, then, that a <code>continue</code> statement always completes abruptly.<p>
<a name="6136"></a>
See the descriptions of the <code>while</code> statement <a href="14.doc.html#237277">(&#167;14.10)</a>, <code>do</code> statement <a href="14.doc.html#6045">(&#167;14.11)</a>, and <code>for</code> statement <a href="14.doc.html#24588">(&#167;14.12)</a> for a discussion of the handling of abrupt termination because of <code>continue</code>.<p>
<a name="43422"></a>
The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any <code>try</code> statements <a href="14.doc.html#79311">(&#167;14.18)</a> within the continue target whose <code>try</code> blocks contain the <code>continue</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements are executed, in order, innermost to outermost, before control is transferred to the continue target. Abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>continue</code> statement.<p>
<a name="42935"></a>
In the <code>Graph</code> example in the preceding section, one of the <code>break</code> statements is used to finish execution of the entire body of the outermost <code>for</code> loop. This <code>break</code> can be replaced by a <code>continue</code> if the <code>for</code> loop itself is labeled:<p>
<pre><a name="42900"></a>
class Graph {
<a name="42901"></a>	. . .
<a name="42903"></a>	public Graph loseEdges(int i, int j) {
<a name="42904"></a>		int n = edges.length;
<a name="42905"></a>		int[][] newedges = new int[n][];
<a name="42906"></a>
		edgelists: for (int k = 0; k &lt; n; ++k) {
<a name="42908"></a>			int z;
<a name="42909"></a>
			search: {
<a name="42989"></a>				if (k == i) {
<a name="42990"></a>					. . .
<a name="42991"></a>				} else if (k == j) {
<a name="42916"></a>					. . .
<a name="42919"></a>				}
<a name="42921"></a>				newedges[k] = edges[k];
<a name="42922"></a>				continue edgelists;
<a name="42923"></a>			}//search
<a name="42925"></a>			. . .
<a name="42983"></a>		}//edgelists
<a name="42932"></a>		return new Graph(newedges);
<a name="42933"></a>	}
<a name="42934"></a>}
</pre><a name="42984"></a>
Which to use, if either, is largely a matter of programming style.
<p><a name="6767"></a>
<h2>14.15    The <code>return</code> Statement</h2>
<a name="124158"></a>
A <code>return</code> statement returns control to the invoker of a method (<a href="8.doc.html#40420">&#167;8.4</a>, <a href="15.doc.html#20448">&#167;15.11</a>) or 
constructor (<a href="8.doc.html#41652">&#167;8.6</a>, <a href="15.doc.html#41147">&#167;15.8</a>).
<p><ul><pre>
<i>ReturnStatement:<br>
</i>	<code>return </code><i>Expression</i><sub><i>opt</i></sub><code> ;
</code></pre></ul><a name="236030"></a>
A <code>return</code> statement with no <i>Expression </i>must be contained in the body of a method that is declared, using the keyword <code>void</code>, not to return any value <a href="8.doc.html#40420">(&#167;8.4)</a>, or in the body of a constructor <a href="8.doc.html#41652">(&#167;8.6)</a>. A compile-time error occurs if a <code>return</code> statement appears within a static initializer <a href="8.doc.html#39245">(&#167;8.5)</a>. A <code>return</code> statement with no <i>Expression</i> attempts to transfer control to the invoker of the method or constructor that contains it. To be precise, a <code>return</code> statement with no <i>Expression</i> always completes abruptly, the reason being a <code>return</code> with no value.<p>
<a name="6148"></a>
A <code>return</code> statement with an <i>Expression</i> must be contained in a method declaration that is declared to return a value <a href="8.doc.html#40420">(&#167;8.4)</a> or a compile-time error occurs. The <i>Expression</i> must denote a variable or value of some type <i>T</i>, or a compile-time error occurs. The type <em>T</em> must be assignable <a href="5.doc.html#170768">(&#167;5.2)</a> to the declared result type of the method, or a compile-time error occurs.<p>
<a name="43489"></a>
A <code>return</code> statement with an <i>Expression</i> attempts to transfer control to the invoker of the method that contains it; the value of the <i>Expression</i> becomes the value of the method invocation. More precisely, execution of such a <code>return</code> statement first evaluates the <i>Expression</i>. If the evaluation of the <i>Expression</i> completes abruptly for some reason, then the <code>return</code> statement completes abruptly for that reason. If evaluation of the <i>Expression</i> completes normally, producing a value <i>V</i>, then the <code>return</code> statement completes abruptly, the reason being a <code>return</code> with value <i>V</i>.<p>
<a name="43495"></a>
It can be seen, then, that a <code>return</code> statement always completes abruptly.<p>
<a name="43508"></a>
The preceding descriptions say "attempts to transfer control" rather than just "transfers control" because if there are any <code>try</code> statements <a href="14.doc.html#79311">(&#167;14.18)</a> within the method or constructor whose <code>try</code> blocks contain the <code>return</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>return</code> statement.<p>
<a name="237350"></a>
<h2>14.16    The <code>throw</code> Statement</h2>
<a name="79254"></a>
A <code>throw</code> statement causes an exception <a href="11.doc.html#44043">(&#167;11)</a> to be thrown. The result is an immediate
transfer of control <a href="11.doc.html#44153">(&#167;11.3)</a> that may exit multiple statements and multiple 
constructor, static and field initializer evaluations, and method invocations until a 
<code>try</code> statement <a href="14.doc.html#79311">(&#167;14.18)</a> is found that catches the thrown value. If no such <code>try</code> 
statement is found, then execution of the thread (<a href="17.doc.html#26250">&#167;17</a>, <a href="javalang.doc18.html#2658">&#167;20.20</a>) that executed the 
<code>throw</code> is terminated <a href="11.doc.html#44153">(&#167;11.3)</a> after invocation of the <code>UncaughtException</code> method 
<a href="javalang.doc19.html#2901">(&#167;20.21.31)</a> for the thread group to which the thread belongs.
<p><ul><pre>
<i>ThrowStatement:<br>
</i>	<code>throw </code><i>Expression</i><code> ;
</code></pre></ul><a name="236072"></a>
The <i>Expression</i> in a throw statement must denote a variable or value of a reference type which is assignable <a href="5.doc.html#170768">(&#167;5.2)</a> to the type <code>Throwable</code>, or a compile-time error occurs. Moreover, at least one of the following three conditions must be true, or a compile-time error occurs:<p>
<ul><a name="236073"></a>
<li>The exception is not a checked exception <a href="11.doc.html#44121">(&#167;11.2)</a>-specifically, one of the following situations is true:
<ul>
<a name="39922"></a>
<li>The type of the <i>Expression</i> is the class <code>RuntimeException</code> or a subclass of <code>RuntimeException</code>.
<a name="236074"></a>
<li>The type of the <i>Expression</i> is the class <code>Error</code> or a subclass of <code>Error</code>.
</ul>
<a name="236078"></a>
<li>The <code>throw</code> statement is contained in the <code>try</code> block of a <code>try</code> statement <a href="14.doc.html#79311">(&#167;14.18)</a> and the type of the <i>Expression</i> is assignable <a href="5.doc.html#170768">(&#167;5.2)</a> to the type of the parameter of at least one <code>catch</code> clause of the <code>try</code> statement. (In this case we say the thrown value is <i>caught</i> by the <code>try</code> statement.)
<a name="236082"></a>
<li>The <code>throw</code> statement is contained in a method or constructor declaration and the type of the <i>Expression</i> is assignable <a href="5.doc.html#170768">(&#167;5.2)</a> to at least one type listed in the <code>throws</code> clause (<a href="8.doc.html#78323">&#167;8.4.4</a>, <a href="8.doc.html#244611">&#167;8.6.4</a>) of the declaration.
</ul><a name="236055"></a>
A <code>throw</code> statement first evaluates the <i>Expression</i>. If the evaluation of the <i>Expression</i> completes abruptly for some reason, then the <code>throw</code> completes abruptly for that reason. If evaluation of the <i>Expression</i> completes normally, producing a value <i>V</i>, then the <code>throw</code> statement completes abruptly, the reason being a <code>throw</code> with value <i>V</i>.<p>
<a name="43545"></a>
It can be seen, then, that a <code>throw</code> statement always completes abruptly.<p>
<a name="43541"></a>
If there are any enclosing <code>try</code> statements <a href="14.doc.html#79311">(&#167;14.18)</a> whose <code>try</code> blocks contain the <code>throw</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>throw</code> statement.<p>
<a name="79283"></a>
If a <code>throw</code> statement is contained in a method declaration, but its value is not caught by some <code>try</code> statement that contains it, then the invocation of the method completes abruptly because of the <code>throw</code>.<p>
<a name="79284"></a>
If a <code>throw</code> statement is contained in a constructor declaration, but its value is not caught by some <code>try</code> statement that contains it, then the class instance creation expression (or the method invocation of method <code>newInstance</code> of class <code>Class</code>) that invoked the constructor will complete abruptly because of the <code>throw</code>.<p>
<a name="43567"></a>
If a <code>throw</code> statement is contained in a static initializer <a href="8.doc.html#39245">(&#167;8.5)</a>, then a compile-time check ensures that either its value is always an unchecked exception or its value is always caught by some <code>try</code> statement that contains it. If, despite this check, the value is not caught by some <code>try</code> statement that contains the <code>throw</code> statement, then the value is rethrown if it is an instance of class <code>Error</code> or one of its subclasses; otherwise, it is wrapped in an <code>ExceptionInInitializerError</code> object, which is then thrown <a href="12.doc.html#44630">(&#167;12.4.2)</a>.<p>
<a name="79285"></a>
By convention, user-declared throwable types should usually be declared to be subclasses of class <code>Exception</code>, which is a subclass of class <code>Throwable</code> (<a href="11.doc.html#44278">&#167;11.5</a>, <a href="javalang.doc20.html#46198">&#167;20.22</a>).<p>
<a name="79287"></a>
<h2>14.17    The <code>synchronized</code> Statement</h2>
<a name="79291"></a>
A <code>synchronized</code> statement acquires a mutual-exclusion lock <a href="17.doc.html#28460">(&#167;17.13)</a> on behalf 
of the executing thread, executes a block, then releases the lock. While the executing
thread owns the lock, no other thread may acquire the lock.
<p><ul><pre>
<i>SynchronizedStatement:<br>
</i>	<code>synchronized ( </code><i>Expression</i><code> ) </code><i>Block
</i></pre></ul><a name="217233"></a>
The type of <i>Expression</i> must be a reference type, or a compile-time error occurs. 
<p><a name="217245"></a>
A <code>synchronized</code> statement is executed by first evaluating the <i>Expression</i>.<p>
<a name="236514"></a>
If evaluation of the <i>Expression</i> completes abruptly for some reason, then the <code>synchronized</code> statement completes abruptly for the same reason.<p>
<a name="236515"></a>
Otherwise, if the value of the <i>Expression</i> is <code>null</code>, a <code>NullPointerException</code> is thrown.<p>
<a name="79295"></a>
Otherwise, let the non-<code>null</code> value of the <i>Expression</i> be <i>V</i>. The executing thread locks the lock associated with <i>V</i>. Then the <i>Block </i>is executed. If execution of the <i>Block</i> completes normally, then the lock is unlocked and the <code>synchronized</code> statement completes normally. If execution of the <i>Block</i> completes abruptly for any reason, then the lock is unlocked and the <code>synchronized</code> statement then completes abruptly for the same reason.<p>
<a name="79305"></a>
Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use <code>synchronized</code> methods or the <code>synchronized</code> &#32;statement in a conventional manner to achieve mutual exclusion.<p>
<a name="79306"></a>
The locks acquired by <code>synchronized</code> statements are the same as the locks that are acquired implicitly by <code>synchronized</code> methods; see <a href="8.doc.html#55408">&#167;8.4.3.5</a>. A single thread may hold a lock more than once. The example:<p>
<pre><a name="237226"></a>
class Test {
<a name="237227"></a>	public static void main(String[] args) {
<a name="237228"></a>		Test t = new Test();
<a name="22894"></a>		synchronized(t) {
<a name="22895"></a>			synchronized(t) {
<a name="22896"></a>				System.out.println("made it!");
<a name="22897"></a>			}
<a name="22898"></a>		}
<a name="22899"></a>	}
<a name="22900"></a>}
</pre><a name="22901"></a>
prints:
<p><pre><a name="22902"></a>made it!
</pre><a name="22903"></a>
This example would deadlock if a single thread were not permitted to lock a lock 
more than once.
<p><a name="79311"></a>
<h2>14.18    The <code>try</code> statement</h2>
<a name="79312"></a>
A <code>try</code> statement executes a block. If a value is thrown and the <code>try</code> statement has 
one or more <code>catch</code> clauses that can catch it, then control will be transferred to the 
first such <code>catch</code> clause. If the <code>try</code> statement has a <code>finally</code> clause, then another 
block of code is executed, no matter whether the <code>try</code> block completes normally or 
abruptly, and no matter whether a <code>catch</code> clause is first given control.
<p><ul><pre>
<i>TryStatement:<br>
</i><code>	try </code><i>Block</i><code> </code><i>Catches<br>
</i><code>	try </code><i>Block</i><code> </code><i>Catches</i><sub><i>opt</i></sub><code> </code><i>Finally
</i>
<i>Catches:<br>
</i>	<i>CatchClause<br>
</i>	<i>Catches</i><code> </code><i>CatchClause
</i>
<i>CatchClause:<br>
</i>	<code>catch ( </code><i>FormalParameter</i><code> ) </code><i>Block
</i>
<i>Finally:<br>
</i><code>	finally </code><i>Block
</i></pre></ul><a name="45818"></a>
The following is repeated from <a href="8.doc.html#38698">&#167;8.4.1</a> to make the presentation here clearer:
<p><ul><pre>
<i>FormalParameter:<br>
</i>	<i>Type</i><code> </code><i>VariableDeclaratorId
</i></pre></ul><a name="237406"></a>
The following is repeated from <a href="8.doc.html#40898">&#167;8.3</a> to make the presentation here clearer:
<p><ul><pre>
<i>VariableDeclaratorId:<br>
</i>	<i>Identifier<br>
</i>	<i>VariableDeclaratorId</i><code> [ ]
</code></pre></ul><a name="79317"></a>
The <i>Block</i> immediately after the keyword <code>try</code> is called the <code>try</code> block of the <code>try</code> statement. The <i>Block</i> immediately after the keyword <code>finally</code> is called the <code>finally</code> block of the <code>try</code> statement.<p>
<a name="79318"></a>
A <code>try</code> statement may have <code>catch</code> clauses (also called <i>exception handlers</i>). A &#32;<code>catch</code> clause must have exactly one parameter (which is called an <i>exception parameter</i>); the declared type of the exception parameter must be the class <code>Throwable</code> or a subclass of <code>Throwable</code>, or a compile-time error occurs. The scope of the parameter variable is the <i>Block</i> of the <code>catch</code> clause. An exception parameter must not have the same name as a local variable or parameter in whose scope it is declared, or a compile-time error occurs.<p>
<a name="45876"></a>
The scope of the name of an exception parameter is the <i>Block</i> of the <code>catch</code> clause. The name of the parameter may not be redeclared as a local variable or exception parameter within the <i>Block</i> of the <code>catch</code> clause; that is, hiding the name of an exception parameter is not permitted.<p>
<a name="45880"></a>
Exception parameters cannot be referred to using qualified names <a href="6.doc.html#33916">(&#167;6.6)</a>, only by simple names.<p>
<a name="24142"></a>
Exception handlers are considered in left-to-right order: the earliest possible <code>catch</code> clause accepts the exception, receiving as its actual argument the thrown exception object.<p>
<a name="24143"></a>
A <code>finally</code> clause ensures that the <code>finally</code> block is executed after the <code>try</code> block and any <code>catch</code> block that might be executed, no matter how control leaves the <code>try</code> block or <code>catch</code> block.<p>
<a name="79319"></a>
Handling of the <code>finally</code> block is rather complex, so the two cases of a <code>try</code> statement with and without a <code>finally</code> block are described separately.<p>
<a name="24134"></a>
<h3>14.18.1    Execution of <code>try-catch</code></h3>
<a name="79320"></a>
A <code>try</code> statement without a <code>finally</code> block is executed by first executing the <code>try</code> 
block. Then there is a choice:
<p><ul><a name="79321"></a>
<li>If execution of the <code>try</code> block completes normally, then no further action is taken and the <code>try</code> statement completes normally.
<a name="79322"></a>
<li>If execution of the <code>try</code> block completes abruptly because of a <code>throw</code> of a value <i>V</i>, then there is a choice:
<ul>
<a name="79323"></a>
<li>If the run-time type of <i>V</i><i></i> is assignable <a href="5.doc.html#170768">(&#167;5.2)</a> to the <i>Parameter</i> of any <code>catch</code> clause of the <code>try</code> statement, then the first (leftmost) such <code>catch</code> clause is selected. The value <i>V</i><i></i> is assigned to the parameter of the selected <code>catch</code> clause, and the <i>Block</i> of that <code>catch</code> clause is executed. If that block completes normally, then the <code>try</code> statement completes normally; if that block completes abruptly for any reason, then the <code>try</code> statement completes abruptly for the same reason.
<a name="79324"></a>
<li>If the run-time type of <i>V</i><i></i> is not assignable to the parameter of any <code>catch</code> clause of the <code>try</code> statement, then the <code>try</code> statement completes abruptly because of a <code>throw</code> of the value <i>V</i>.
</ul>
<a name="79325"></a>
<li>If execution of the <code>try</code> block completes abruptly for any other reason, then the <code>try</code> statement completes abruptly for the same reason.
</ul><a name="18065"></a>
In the example:
<p><pre><a name="18066"></a>class BlewIt extends Exception {
<a name="236619"></a>	BlewIt() { }
<a name="236620"></a>	BlewIt(String s) { super(s); }
<a name="236621"></a>}
<a name="236622"></a>class Test {
<a name="236623"></a>	static void blowUp() throws BlewIt { throw new BlewIt(); }
<a name="237378"></a>	public static void main(String[] args) {
</pre><pre><a name="236625"></a>
		try {
<a name="236626"></a>			blowUp();
<a name="236627"></a>		} catch (RuntimeException r) {
<a name="236628"></a>			System.out.println("RuntimeException:" + r);
<a name="236629"></a>		} catch (BlewIt b) {
<a name="236630"></a>			System.out.println("BlewIt");
<a name="236631"></a>		}
<a name="236632"></a>	}
<br><a name="236633"></a>}
</pre><a name="236651"></a>
the exception <code>BlewIt</code> is thrown by the method <code>blowUp</code>. The <code>try</code><strong>-</strong><code>catch</code> statement 
in the body of <code>main</code> has two <code>catch</code> clauses. The run-time type of the exception is 
<code>BlewIt</code> which is not assignable to a variable of type <code>RuntimeException</code>, but is 
assignable to a variable of type <code>BlewIt</code>, so the output of the example is:
<p><pre><a name="236656"></a>BlewIt
</pre><a name="236653"></a>
<h3>14.18.2    Execution of <code>try-catch-finally</code></h3>
<a name="79326"></a>
A <code>try</code> statement with a <code>finally</code> block is executed by first executing the <code>try</code> 
block. Then there is a choice:
<p><ul><a name="79327"></a>
<li>If execution of the <code>try</code> block completes normally, then the <code>finally</code> block is executed, and then there is a choice:
<ul>
<a name="160341"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes normally.
<a name="160342"></a>
<li>If the <code>finally</code> block completes abruptly for reason <i>S</i>, then the <code>try</code> statement completes abruptly for reason <i>S</i><i></i>.
</ul>
<a name="79328"></a>
<li>If execution of the <code>try</code> block completes abruptly because of a <code>throw</code> of a value <i>V</i>, then there is a choice:
<ul>
<a name="79329"></a>
<li>If the run-time type of <i>V</i><i></i> is assignable to the parameter of any <code>catch</code> clause of the <code>try</code> statement, then the first (leftmost) such <code>catch</code> clause is selected. The value <i>V</i><i></i> is assigned to the parameter of the selected <code>catch</code> clause, and the <i>Block</i> of that <code>catch</code> clause is executed. Then there is a choice:
<ul>
<a name="79330"></a>
<li>If the <code>catch</code> block completes normally, then the <code>finally</code> block is executed. Then there is a choice:
<ul>
<a name="160348"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes normally.
<a name="160349"></a>
<li>If the <code>finally</code> block completes abruptly for any reason, then the <code>try</code> statement completes abruptly for the same reason.
</ul>
<a name="79331"></a>
<li>If the <code>catch</code> block completes abruptly for reason <i>R</i><i></i>, then the <code>finally</code> block is executed. Then there is a choice:
<ul>
<a name="79332"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes abruptly for reason <i>R</i><i></i>.
<a name="79333"></a>
<li>If the <code>finally</code> block completes abruptly for reason <i>S</i>, then the <code>try</code> statement completes abruptly for reason <i>S</i><i></i> (and reason <i>R</i><i></i> is discarded).
</ul>
</ul>
<a name="79334"></a>
<li>If the run-time type of <i>V</i><i></i> is not assignable to the parameter of any <code>catch</code> clause of the <code>try</code> statement, then the <code>finally</code> block is executed. Then there is a choice:
<ul>
<a name="79335"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes abruptly because of a <code>throw</code> of the value <i>V</i>.
<a name="79336"></a>
<li>If the <code>finally</code> block completes abruptly for reason <i>S</i>, then the <code>try</code> statement completes abruptly for reason <i>S</i><i></i> (and the <code>throw</code> of value <i>V</i><i></i> is discarded and forgotten).
</ul>
</ul>
<a name="79337"></a>
<li>If execution of the <code>try</code> block completes abruptly for any other reason <i>R</i><i></i>, then the <code>finally</code> block is executed. Then there is a choice:
<ul>
<a name="79338"></a>
<li>If the <code>finally</code> block completes normally, then the <code>try</code> statement completes abruptly for reason <i>R</i><i></i>.
<a name="79339"></a>
<li>If the <code>finally</code> block completes abruptly for reason <i>S</i>, then the <code>try</code> statement completes abruptly for reason <i>S</i><i></i> (and reason <i>R</i><i></i> is discarded).
</ul>
</ul><a name="18069"></a>
The example:
<p><pre><a name="236658"></a>class BlewIt extends Exception {
<a name="236659"></a>	BlewIt() { }
<a name="236660"></a>	BlewIt(String s) { super(s); }
<a name="236661"></a>}
</pre><pre><a name="236662"></a>
class Test {
<a name="236663"></a>
	static void blowUp() throws BlewIt {<br>
		throw new NullPointerException();<br>
	}
<a name="236664"></a>
	public static void main(String[] args) {
<a name="236665"></a>		try {
<a name="236666"></a>			blowUp();
<a name="236669"></a>		} catch (BlewIt b) {
<a name="236670"></a>			System.out.println("BlewIt");
<a name="236671"></a>		} finally {
<a name="236685"></a>			System.out.println("Uncaught Exception");
<a name="236686"></a>		}
<a name="236672"></a>	}
<br><a name="236673"></a>}
</pre><a name="18070"></a>
produces the output:
<p><pre><a name="236697"></a>
Uncaught Exception
<a name="236698"></a>java.lang.NullPointerException
<a name="236699"></a>	at Test.blowUp(Test.java:7)
<a name="236700"></a>	at Test.main(Test.java:11)
</pre><a name="236703"></a>
The <code>NullPointerException</code> (which is a kind of <code>RuntimeException</code>) that is 
thrown by method <code>blowUp</code> is not caught by the <code>try</code> statement in <code>main</code>, because a 
<code>NullPointerException</code> is not assignable to a variable of type <code>BlewIt</code>. This 
causes the <code>finally</code> clause to execute, after which the thread executing <code>main</code>, 
which is the only thread of the test program, terminates because of an uncaught 
exception <a href="javalang.doc19.html#2901">(&#167;20.21.31)</a>, which results in printing the exception name and a simple 
backtrace.
<p><a name="236365"></a>
<h2>14.19    Unreachable Statements</h2>
<a name="237365"></a>
It is a compile-time error if a statement cannot be executed because it is <i>unreachable
</i>. Every Java compiler must carry out the conservative flow analysis specified 
here to make sure all statements are reachable.
<p><a name="237366"></a>
This section is devoted to a precise explanation of the word "reachable." The idea is that there must be some possible execution path from the beginning of the constructor, method, or static initializer that contains the statement to the statement itself. The analysis takes into account the structure of statements. Except for the special treatment of <code>while</code>, <code>do</code>, and <code>for</code> statements whose condition expression has the constant value <code>true</code>, the values of expressions are not taken into account in the flow analysis. For example, a Java compiler will accept the code:<p>
<pre><a name="79345"></a>
{
<a name="79347"></a>	int n = 5;
<a name="79348"></a>	while (n &gt; 7) n = 2;
<a name="79349"></a>}
</pre><a name="79350"></a>
even though the value of <code>n</code> is known at compile time and in principle it can be 
known at compile time that the assignment to <code>k</code> can never be executed. A Java 
compiler must operate according to the rules laid out in this section.
<p><a name="79351"></a>
The rules in this section define two technical terms:<p>
<ul><a name="79352"></a>
<li>whether a statement is <i>reachable</i>
<a name="79353"></a>
<li>whether a statement <i>can complete normally</i>
</ul><a name="79354"></a>
The definitions here allow a statement to complete normally only if it is reachable.
<p><a name="236611"></a>
To shorten the description of the rules, the customary abbreviation "iff" is used to mean "if and only if."<p>
<a name="236612"></a>
The rules are as follows:<p>
<ul><a name="236613"></a>
<li>The block that is the body of a constructor, method, or static initializer is reachable.
<a name="160362"></a>
<li>An empty block that is not a switch block can complete normally iff it is reachable. A nonempty block that is not a switch block can complete normally iff the last statement in it can complete normally. The first statement<i></i> in a nonempty block that is not a switch block is reachable iff the block is reachable. Every other statement <i>S</i><i></i> in a nonempty block that is not a switch block is reachable iff the statement preceding <i>S</i><i></i> can complete normally.
<a name="160365"></a>
<li>A local variable declaration statement can complete normally iff it is reachable.
<a name="79357"></a>
<li>An empty statement can complete normally iff it is reachable.
<a name="79359"></a>
<li>A labeled statement can complete normally if at least one of the following is true:
<ul>
<a name="21184"></a>
<li>The contained statement can complete normally.
<a name="21188"></a>
<li>There is a reachable <code>break</code> statement that exits the labeled statement.
</ul>
</ul><ul><a name="21187"></a>
<br><br>The contained statement is reachable iff the labeled statement is reachable.
</ul><ul><a name="79360"></a>
<li>An expression statement can complete normally iff it is reachable.
<a name="236410"></a>
<li>The <code>if</code> statement, whether or not it has an <code>else</code> part, is handled in an unusual manner. For this reason, it is discussed separately at the end of this section.
<a name="79366"></a>
<li>A <code>switch</code> statement can complete normally iff at least one of the following is true:
<ul>
<a name="79367"></a>
<li>The last statement in the switch block can complete normally.
<a name="237563"></a>
<li>The switch block is empty or contains only switch labels.
<a name="237564"></a>
<li>There is at least one switch label after the last switch block statement group.
<a name="79368"></a>
<li>There is a reachable <code>break</code> statement that exits the <code>switch</code> statement.
</ul>
<a name="237548"></a>
<li>A switch block is reachable iff its <code>switch</code> statement is reachable.
<a name="237550"></a>
<li>A statement in a switch block is reachable iff its <code>switch</code> statement is reachable and at least one of the following is true:
<ul>
<a name="79370"></a>
<li>It bears a <code>case</code> or <code>default</code> label.
<a name="79371"></a>
<li>There is a statement preceding it in the <code>switch</code> block and that preceding statement can complete normally.
</ul>
<a name="79372"></a>
<li>A <code>while</code> statement can complete normally iff at least one of the following is true:
<ul>
<a name="79373"></a>
<li>The <code>while</code> statement is reachable and the condition expression is not a constant expression with value <code>true</code>.
<a name="79374"></a>
<li>There is a reachable <code>break</code> statement that exits the <code>while</code> statement.
</ul>
</ul><ul><a name="79375"></a>
<br><br>The contained statement is reachable iff the <code>while</code> statement is reachable and the condition expression is not a constant expression whose value is <code>false</code>.
</ul><ul><a name="79376"></a>
<li>A <code>do</code> statement can complete normally iff at least one of the following is true:
<ul>
<a name="79377"></a>
<li>The contained statement can complete normally and the condition expression is not a constant expression with value <code>true</code>.
<a name="79378"></a>
<li>There is a reachable <code>break</code> statement that exits the <code>do</code> statement.
</ul>
</ul><ul><a name="79379"></a>
<br><br>The contained statement is reachable iff the <code>do</code> statement is reachable.
</ul><ul><a name="79380"></a>
<li>A <code>for</code> statement can complete normally iff at least one of the following is true:
<ul>
<a name="79381"></a>
<li>The <code>for</code> statement is reachable, there is a condition expression, and the condition expression is not a constant expression with value <code>true</code>.
<a name="79382"></a>
<li>There is a reachable <code>break</code> statement that exits the <code>for</code> statement.
</ul>
</ul><ul><a name="79383"></a>
<br><br>The contained statement is reachable iff the <code>for</code> statement is reachable and the condition expression is not a constant expression whose value is <code>false</code>.
</ul><ul><a name="79384"></a>
<li>A <code>break</code>, <code>continue</code>, <code>return</code>, or <code>throw</code> statement cannot complete normally.
<a name="79385"></a>
<li>A <code>synchronized</code> statement can complete normally iff the contained statement can complete normally. The contained statement is reachable iff the <code>synchronized</code> statement is reachable.
<a name="79386"></a>
<li>A <code>try</code> statement can complete normally iff both of the following are true:
<ul>
<a name="79387"></a>
<li>The <code>try</code> block can complete normally or any <code>catch</code> block can complete <code>normally</code>.
<a name="79388"></a>
<li>If the <code>try</code> statement has a <code>finally</code> block, then the <code>finally</code> block can complete normally.
</ul>
<a name="79389"></a>
<li>The <code>try</code> block is reachable iff the <code>try</code> statement is reachable.
<a name="79390"></a>
<li>A <code>catch</code> block <i>C</i> is reachable iff both of the following are true:
<ul>
<a name="79391"></a>
<li>Some expression or <code>throw</code> statement in the <code>try</code> block is reachable and can throw an exception whose type is assignable to the parameter of the <code>catch</code> clause <i>C</i>. (An expression is considered reachable iff the innermost statement containing it is reachable.)
<a name="79392"></a>
<li>There is no earlier <code>catch</code> block <i>A</i> in the <code>try</code> statement such that the type of <i>C</i>'s parameter is the same as or a subclass of the type of <i>A</i>'s parameter.
</ul>
<a name="236212"></a>
<li>If a <code>finally</code> block is present, it is reachable iff the <code>try</code> statement is reachable.
</ul><a name="236419"></a>
One might expect the <code>if</code> statement to be handled in the following manner, but these are not the rules that Java actually uses:<p>
<ul><a name="236554"></a>
<li>HYPOTHETICAL: An <code>if-then</code> statement can complete normally iff at least one of the following is <code>true</code>:
<ul>
<a name="236555"></a>
<li>The <code>if</code>-<code>then</code> statement is reachable and the condition expression is not a constant expression whose value is <code>true</code>.
<a name="236407"></a>
<li>The <code>then</code>-statement can complete normally.
</ul>
</ul><ul><a name="236408"></a>
<br><br>The <code>then</code>-statement is reachable iff the <code>if</code>-<code>then</code> statement is reachable and the condition expression is not a constant expression whose value is <code>false</code>.
</ul><ul><a name="236409"></a>
<li>HYPOTHETICAL: An <code>if</code>-<code>then</code>-<code>else</code> statement can complete normally iff the <code>then</code>-statement can complete normally or the <code>else</code>-statement can complete normally. The <code>then</code>-statement is reachable iff the <code>if</code>-<code>then</code>-<code>else</code> statement is reachable and the condition expression is not a constant expression whose value is <code>false</code>. The <code>else</code> statement is reachable iff the <code>if</code>-<code>then</code>-<code>else </code>statement is reachable and the condition expression is not a constant expression whose value is <code>true</code>.
</ul><a name="236422"></a>
This approach would be consistent with the treatment of other control structures 
in Java. However, in order to allow the if statement to be used conveniently for 
"conditional compilation" purposes, the actual rules are as follows:
<p><ul><a name="236424"></a>
<li>ACTUAL: An <code>if</code>-<code>then</code> statement can complete normally iff it is reachable. The <code>then</code>-statement is reachable iff the <code>if</code>-<code>then</code> statement is reachable.
<a name="236428"></a>
<li>ACTUAL: An <code>if</code>-<code>then</code>-<code>else</code> statement can complete normally iff the <code>then</code>-statement can complete normally or the <code>else</code>-statement can complete normally. The <code>then</code>-statement is reachable iff the <code>if</code>-<code>then</code>-<code>else</code> statement is reachable. The <code>else</code>-statement is reachable iff the <code>if</code>-<code>then</code>-<code>else</code> statement is reachable.
</ul><a name="236451"></a>
As an example, the following statement results in a compile-time error:
<p><pre><a name="236452"></a>while (false) { x=3; }
</pre><a name="236453"></a>
because the statement <code>x=3;</code> is not reachable; but the superficially similar case:
<p><pre><a name="236456"></a>if (false) { x=3; }
</pre><a name="236454"></a>
does not result in a compile-time error. An optimizing compiler may realize that 
the statement <code>x=3;</code> will never be executed and may choose to omit the code for 
that statement from the generated <code>class</code> file, but the statement <code>x=3;</code> is not 
regarded as "unreachable" in the technical sense specified here.
<p><a name="238244"></a>
The rationale for this differing treatment is to allow programmers to define "flag variables" such as:<p>
<pre><a name="236464"></a>static final boolean DEBUG = false;
</pre><a name="236471"></a>
and then write code such as:
<p><pre><a name="236466"></a>if (DEBUG) { x=3; }
</pre><a name="236477"></a>
The idea is that it should be possible to change the value of <code>DEBUG</code> from <code>false</code> to 
<code>true</code> or from <code>true</code> to <code>false</code> and then compile the code correctly with no other 
changes to the program text.
<p><a name="238425"></a>
This ability to "conditionally compile" has a significant impact on, and relationship to, binary compatibility <a href="13.doc.html#44871">(&#167;13)</a>. If a set of classes that use such a "flag" variable are compiled and conditional code is omitted, it does not suffice later to distribute just a new version of the class or interface that contains the definition of the flag. A change to the value of a flag is, therefore, not binary compatible with preexisting binaries <a href="13.doc.html#45139">(&#167;13.4.8)</a>. (There are other reasons for such incompatibility as well, such as the use of constants in <code>case</code> labels in <code>switch</code> statements; see <a href="13.doc.html#45139">&#167;13.4.8</a>.)<p>
<a name="246702"></a>
<p>
<a name="241248"></a>
<p>
<a name="241250"></a>
<p>
<a name="241251"></a>
<p>
<a name="241252"></a>
<p>
<a name="241253"></a>
<p>
<a name="241254"></a>
<p>
<a name="241255"></a>
<p>
<a name="241256"></a>
<p>
<a name="241257"></a>
<p>
<a name="241258"></a>
<p>
<a name="241259"></a>
<p>
<a name="241260"></a>
<p>
<a name="241261"></a>
<p>
<a name="241262"></a>
<p>
<a name="241263"></a>
<p>
<a name="241264"></a>
<p>
<a name="241265"></a>
<p>
<a name="241266"></a>
<p>
<a name="241267"></a>
<p>


<hr>
<!-- This inserts footnotes-->
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="13.doc.html">Prev</a> | <a href="15.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<p>
<font size=-1>Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)<br>
<i><a href="jcopyright.doc.html">Copyright &#169 1996 Sun Microsystems, Inc.</a>
All rights reserved</i>
<br>
Please send any comments or corrections via our <a href="http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback">feedback form</a>
</font>
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body></html><html>
<head>
<meta name="collection" content="exclude">

<title>The Java Language Specification
 Expressions</title>
</head>
<body BGCOLOR=#eeeeff text=#000000 LINK=#0000ff VLINK=#000077 ALINK=#ff0000>
 
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="14.doc.html">Prev</a> | <a href="16.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<hr><br>
 
<a name="4709"></a>
<p><strong>
CHAPTER
 15 </strong></p>
<a name="44393"></a>
<h1>Expressions</h1>
<hr><p>
<a name="11757"></a>
Much of the work in a Java program is done by evaluating <i>expressions</i>, either 
for their side effects, such as assignments to variables, or for their values, which 
can be used as arguments or operands in larger expressions, or to affect the execution
sequence in statements, or both.
<p><a name="236101"></a>
This chapter specifies the meanings of Java expressions and the rules for their evaluation.<p>
<a name="228862"></a>
<h2>15.1    Evaluation, Denotation, and Result</h2>
<a name="228864"></a>
When an expression in a Java program is <i>evaluated</i> (<i>executed</i>), the <i>result</i> denotes 
one of three things:
<p><ul><a name="228896"></a>
<li>A variable <a href="4.doc.html#18470">(&#167;4.5)</a> (in C, this would be called an <i>lvalue</i>)
<a name="19788"></a>
<li>A value (<a href="4.doc.html#85587">&#167;4.2</a>, <a href="4.doc.html#9317">&#167;4.3</a>)
<a name="229505"></a>
<li>Nothing (the expression is said to be <code>void</code>)
</ul><a name="233971"></a>
Evaluation of an expression can also produce side effects, because expressions may contain embedded assignments, increment operators, decrement operators, and method invocations.<p>
<a name="229523"></a>
An expression denotes nothing if and only if it is a method invocation <a href="15.doc.html#20448">(&#167;15.11)</a> that invokes a method that does not return a value, that is, a method declared <code>void</code> <a href="8.doc.html#40420">(&#167;8.4)</a>. Such an expression can be used only as an expression statement <a href="14.doc.html#5984">(&#167;14.7)</a>, because every other context in which an expression can appear requires the expression to denote something. An expression statement that is a method invocation may also invoke a method that produces a result; in this case the value returned by the method is quietly discarded.<p>
<a name="39859"></a>
Each expression occurs in the declaration of some (class or interface) type that is being declared: in a field initializer, in a static initializer, in a constructor declaration, or in the code for a method.<p>
<a name="229188"></a>
<h2>15.2    Variables as Values</h2>
<a name="229204"></a>
If an expression denotes a variable, and a value is required for use in further evaluation,
then the value of that variable is used. In this context, if the expression 
denotes a variable or a value, we may speak simply of the <i>value</i> of the expression.
<p><a name="198550"></a>
<h2>15.3    Type of an Expression</h2>
<a name="229255"></a>
If an expression denotes a variable or a value, then the expression has a type 
known at compile time. The rules for determining the type of an expression are 
explained separately below for each kind of expression.
<p><a name="229277"></a>
The value of an expression is always assignment compatible <a href="5.doc.html#170768">(&#167;5.2)</a> with the type of the expression, just as the value stored in a variable is always compatible with the type of the variable. In other words, the value of an expression whose type is <i>T</i> is always suitable for assignment to a variable of type <i>T</i>.<p>
<a name="79417"></a>
Note that an expression whose type is a class type <i>F</i> that is declared <code>final</code> is guaranteed to have a value that is either a null reference or an object whose class is <i>F</i> itself, because <code>final</code> types have no subclasses.<p>
<a name="233992"></a>
<h2>15.4    Expressions and Run-Time Checks</h2>
<a name="233993"></a>
If the type of an expression is a primitive type, then the value of the expression is 
of that same primitive type. But if the type of an expression is a reference type, 
then the class of the referenced object, or even whether the value is a reference to 
an object rather than <code>null</code>, is not necessarily known at compile time. There are a 
few places in the Java language where the actual class of a referenced object 
affects program execution in a manner that cannot be deduced from the type of the 
expression. They are as follows:
<p><ul><a name="79422"></a>
<li>Method invocation <a href="15.doc.html#20448">(&#167;15.11)</a>. The particular method used for an invocation <code>o.m(</code>...<code>)</code> is chosen based on the methods that are part of the class or interface that is the type of <code>o</code>. For instance methods, the class of the object referenced by the run-time value of <code>o</code> participates because a subclass may override a specific method already declared in a parent class so that this overriding method is invoked. (The overriding method may or may not choose to further invoke the original overridden <code>m</code> method.)
<a name="79436"></a>
<li>The <code>instanceof</code> operator <a href="15.doc.html#80289">(&#167;15.19.2)</a>. An expression whose type is a reference type may be tested using <code>instanceof</code> to find out whether the class of the object referenced by the run-time value of the expression is assignment compatible <a href="5.doc.html#170768">(&#167;5.2)</a> with some other reference type.
<a name="35797"></a>
<li>Casting (<a href="5.doc.html#176921">&#167;5.4</a>, <a href="15.doc.html#238146">&#167;15.15</a>). The class of the object referenced by the run-time value of the operand expression might not be compatible with the type specified by the cast. For reference types, this may require a run-time check that throws an error if the class of the referenced object, as determined at run time, is not assignment &#32;compatible <a href="5.doc.html#170768">(&#167;5.2)</a> with the target type.
<a name="35800"></a>
<li>Assignment to an array component of reference type (<a href="10.doc.html#11430">&#167;10.10</a>, <a href="15.doc.html#239587">&#167;15.12</a>, <a href="15.doc.html#5295">&#167;15.25.1</a>). The type-checking rules allow the array type <i>S</i><code>[]</code> to be treated as a subtype of <i>T</i><code>[]</code> if <i>S</i> is a subtype of <i>T</i>, but this requires a run-time check for assignment to an army component, similar to the check performed for a cast.
<a name="79438"></a>
<li>Exception handling <a href="14.doc.html#79311">(&#167;14.18)</a>. An exception is caught by a <code>catch</code> clause only if the class of the thrown exception object is an <code>instanceof</code> the type of the formal parameter of the <code>catch</code> clause.
</ul><a name="35847"></a>
The first two of the cases just listed ought never to result in detecting a type error. 
Thus, a Java run-time type error can occur only in these situations:
<p><ul><a name="79443"></a>
<li>In a cast, when the actual class of the object referenced by the value of the operand expression is not compatible with the target type specified by the cast operator (<a href="5.doc.html#176921">&#167;5.4</a>, <a href="15.doc.html#238146">&#167;15.15</a>); in this case a <code>ClassCastException</code> is thrown.
<a name="79444"></a>
<li>In an assignment to an array component of reference type, when the actual class of the object referenced by the value to be assigned is not compatible with the actual run-time component type of the array (<a href="10.doc.html#11430">&#167;10.10</a>, <a href="15.doc.html#239587">&#167;15.12</a>, <a href="15.doc.html#5295">&#167;15.25.1</a>); in this case an <code>ArrayStoreException</code> is thrown.
<a name="79445"></a>
<li>When an exception is not caught by any <code>catch</code> handler <a href="11.doc.html#44153">(&#167;11.3)</a>; in this case the thread of control that encountered the exception first invokes the method <code>uncaughtException</code> &#32;<a href="javalang.doc19.html#2901">(&#167;20.21.31)</a> for its thread group and then terminates.
</ul><a name="79448"></a>
<h2>15.5    Normal and Abrupt Completion of Evaluation</h2>
<a name="79449"></a>
Every expression has a normal mode of evaluation in which certain computational 
steps are carried out. The following sections describe the normal mode of evaluation
for each kind of expression. If all the steps are carried out without an exception
being thrown, the expression is said to <i>complete normally</i>. 
<p><a name="217304"></a>
If, however, evaluation of an expression throws an exception, then the expression is said to <i>complete abruptly</i>. An abrupt completion always has an associated <i>reason</i>, which is always a <code>throw</code> with a given value.<p>
<a name="217294"></a>
Run-time exceptions are thrown by the predefined operators as follows:<p>
<ul><a name="43791"></a>
<li>A class instance creation expression <a href="15.doc.html#41147">(&#167;15.8)</a>, array creation expression <a href="15.doc.html#46168">(&#167;15.9)</a>, or string concatenation operatior expression <a href="15.doc.html#39990">(&#167;15.17.1)</a> throws an <code>OutOfMemoryError</code> if there is insufficient memory available.
<a name="43795"></a>
<li>An array creation expression throws an <code>ArrayNegativeSizeException</code> if the value of any dimension expression is less than zero <a href="15.doc.html#46168">(&#167;15.9)</a>.
<a name="43780"></a>
<li>A field access <a href="15.doc.html#41267">(&#167;15.10)</a> throws a <code>NullPointerException</code> if the value of the object reference &#32;expression is <code>null</code>.
<a name="43784"></a>
<li>A method invocation expression <a href="15.doc.html#20448">(&#167;15.11)</a> that invokes an instance method throws a <code>NullPointerException</code> if the target reference is <code>null</code>.
<a name="43730"></a>
<li>An array access <a href="15.doc.html#239587">(&#167;15.12)</a> throws a <code>NullPointerException</code> if the value of the array reference &#32;expression is <code>null</code>.
<a name="43758"></a>
<li>An array access <a href="15.doc.html#239587">(&#167;15.12)</a> throws an <code>IndexOutOfBoundsException</code> if the value &#32;of the array index expression is negative or greater than or equal to the <code>length</code> of the array.
<a name="217340"></a>
<li>A cast <a href="15.doc.html#238146">(&#167;15.15)</a> throws a <code>ClassCastException</code> if a cast is found to be impermissible at run time.
<a name="217346"></a>
<li>An integer division <a href="15.doc.html#5047">(&#167;15.16.2)</a> or integer remainder <a href="15.doc.html#24956">(&#167;15.16.3)</a> operator throws an <code>ArithmeticException</code> if the value of the right-hand operand expression is zero.
<a name="234027"></a>
<li>An assignment to an array component of reference type <a href="15.doc.html#5295">(&#167;15.25.1)</a> throws an <code>ArrayStoreException</code> when the value to be assigned is not compatible with the component type of the array.
</ul><a name="21217"></a>
A method invocation expression can also result in an exception being thrown if an 
exception occurs that causes execution of the method body to complete abruptly. 
A class instance creation expression can also result in an exception being thrown 
if an exception occurs that causes execution of the constructor to complete 
abruptly. Various linkage and virtual machine errors may also occur during the 
evaluation of an expression. By their nature, such errors are difficult to predict and 
difficult to handle.
<p><a name="6969"></a>
If an exception occurs, then evaluation of one or more expressions may be terminated before all steps of their normal mode of evaluation are complete; such expressions are said to complete abruptly. The terms "complete normally" and &#32;"complete abruptly" are also applied to the execution of statements <a href="14.doc.html#5894">(&#167;14.1)</a>. A &#32;statement may complete abruptly for a variety of reasons, not just because an exception is thrown.<p>
<a name="79456"></a>
If evaluation of an expression requires evaluation of a subexpression, abrupt completion of the subexpression always causes the immediate abrupt completion of the expression itself, with the same reason, and all succeeding steps in the normal mode of evaluation are not performed.<p>
<a name="4779"></a>
<h2>15.6    Evaluation Order</h2>
<a name="40055"></a>
Java guarantees that the operands of operators appear to be evaluated in a specific 
<i>evaluation order</i>, namely, from left to right.
<p><a name="18532"></a>
It is recommended that Java code not rely crucially on this specification. Code is usually clearer when each expression contains at most one side effect, as its outermost &#32;operation, and when code does not depend on exactly which exception arises as a consequence of the left-to-right evaluation of expressions.<p>
<a name="18498"></a>
<h3>15.6.1    Evaluate Left-Hand Operand First</h3>
<a name="4781"></a>
The left-hand operand of a binary operator appears to be fully evaluated before 
any part of the right-hand operand is evaluated. For example, if the left-hand operand
contains an assignment to a variable and the right-hand operand contains a 
reference to that same variable, then the value produced by the reference will 
reflect the fact that the assignment occurred first.
<p><a name="18540"></a>
Thus:<p>
<pre><a name="18537"></a>
class Test {
<a name="45395"></a>	public static void main(String[] args) {
<a name="18572"></a>		int i = 2;
<a name="18538"></a>		int j = (i=3) * i;
<a name="18573"></a>		System.out.println(j);
<a name="18574"></a>	}
<a name="18575"></a>}
</pre><a name="18539"></a>
prints:
<p><pre><a name="45398"></a><code>9
</code></pre><a name="35994"></a>
It is not permitted for it to print <code>6</code> instead of <code>9</code>.
<p><a name="240786"></a>
If the operator is a compound-assignment operator <a href="15.doc.html#5304">(&#167;15.25.2)</a>, then evaluation of the left-hand operand includes both remembering the variable that the left-hand operand denotes and fetching and saving that variable's value for use in the implied combining operation. So, for example, the test program:<p>
<pre><a name="18711"></a>
class Test {
<a name="18712"></a>	public static void main(String[] args) {
<a name="18713"></a>		int a = 9;
<a name="18714"></a>		a += (a = 3);									// first example
<a name="18715"></a>		System.out.println(a);
<a name="18716"></a>		int b = 9;
<a name="18717"></a>		b = b + (b = 3);									// second example
<a name="18718"></a>		System.out.println(b);
<a name="18719"></a>	}
<a name="18720"></a>}
</pre><a name="18725"></a>
prints:
<p><pre><a name="18726"></a>
12
<a name="18727"></a>12
</pre><a name="18728"></a>
because the two assignment statements both fetch and remember the value of the 
left-hand operand, which is <code>9</code>, before the right-hand operand of the addition is 
evaluated, thereby setting the variable to <code>3</code>. It is not permitted for either example 
to produce the result <code>6</code>. Note that both of these examples have unspecified behavior
in C, according to the ANSI/ISO standard.
<p><a name="4782"></a>
If evaluation of the left-hand operand of a binary operator completes abruptly, no part of the right-hand operand appears to have been evaluated.<p>
<a name="18857"></a>
Thus, the test program:<p>
<pre><a name="18860"></a>
class Test {
<a name="18861"></a>
	public static void main(String[] args) {
<a name="18877"></a>
		int j = 1;
<a name="18863"></a>
		try {
<a name="18864"></a>			int i = forgetIt() / (j = 2);
<a name="18865"></a>		} catch (Exception e) {
<a name="36034"></a>			System.out.println(e);
<a name="18866"></a>			System.out.println("Now j = " + j);
<a name="18867"></a>		}
<a name="18868"></a>	}
<a name="18869"></a>
	static int forgetIt() throws Exception {
<a name="50187"></a>		throw new Exception("I'm outta here!");
<a name="50189"></a>	}
<a name="18870"></a>}
</pre><a name="18858"></a>
prints:
<p><pre><a name="36046"></a>
java.lang.Exception: I'm outta here!
<a name="36047"></a>Now j = 1
</pre><a name="18885"></a>
because the left-hand operand <code>forgetIt()</code> of the operator <code>/</code> throws an exception 
before the right-hand operand and its embedded assignment of <code>2</code> to <code>j</code> occurs.
<p><a name="18740"></a>
<h3>15.6.2    Evaluate Operands before Operation</h3>
<a name="18749"></a>
Java also guarantees that every operand of an operator (except the conditional 
operators <code>&amp;&amp;</code>, <code>||</code>, and <code>?</code> <code>:</code>) appears to be fully evaluated before any part of the 
operation itself is performed.
<p><a name="32910"></a>
If the binary operator is an integer division <code>/</code> <a href="15.doc.html#5047">(&#167;15.16.2)</a> or integer remainder <code>%</code> <a href="15.doc.html#24956">(&#167;15.16.3)</a>, then its execution may raise an <code>ArithmeticException</code>, but this exception is thrown only after both operands of the binary operator have been evaluated and only if these evaluations completed normally.<p>
<a name="36160"></a>
So, for example, the program:<p>
<pre><a name="36161"></a>
class Test {
<a name="36162"></a>
	public static void main(String[] args) {
<a name="36163"></a>		int divisor = 0;
<a name="36164"></a>		try {
<a name="36165"></a>			int i = 1 / (divisor * loseBig());
<a name="36166"></a>		} catch (Exception e) {
<a name="36167"></a>			System.out.println(e);
<a name="36168"></a>		}
<a name="36169"></a>	}
<br><a name="36170"></a>
	static int loseBig() throws Exception {
<a name="36171"></a>		throw new Exception("Shuffle off to Buffalo!");
<a name="36172"></a>	}
<br><a name="36173"></a>}
</pre><a name="36174"></a>
always prints:
<p><pre><a name="36175"></a>java.lang.Exception: Shuffle off to Buffalo!
</pre><a name="36176"></a>
and not:
<p><pre><a name="36177"></a>java.lang.ArithmeticException: / by zero
</pre><a name="36178"></a>
since no part of the division operation, including signaling of a divide-by-zero 
exception, may appear to occur before the invocation of <code>loseBig</code> completes, even 
though the implementation may be able to detect or infer that the division operation
would certainly result in a divide-by-zero exception.
<p><a name="23213"></a>
<h3>15.6.3    Evaluation Respects Parentheses and Precedence</h3>
<a name="23217"></a>
Java implementations must respect the order of evaluation as indicated explicitly 
by parentheses and implicitly by operator precedence. An implementation may 
not take advantage of algebraic identities such as the associative law to rewrite 
expressions into a more convenient computational order unless it can be proven 
that the replacement expression is equivalent in value and in its observable side 
effects, even in the presence of multiple threads of execution (using the thread 
execution model in <a href="17.doc.html#26250">&#167;17</a>), for all possible computational values that might be 
involved.
<p><a name="23218"></a>
In the case of floating-point calculations, this rule applies also for infinity and not-a-number (NaN) values. For example, <code>!(x&lt;y)</code> may not be rewritten as <code>x&gt;=y</code>, because these expressions have different values if either <code>x</code> or <code>y</code> is NaN.<p>
<a name="23219"></a>
Specifically, floating-point calculations that appear to be mathematically associative are unlikely to be computationally associative. Such computations must not be naively reordered. For example, it is not correct for a Java compiler to rewrite <code>4.0*x*0.5</code> as <code>2.0*x</code>; while roundoff happens not to be an issue here, there are large values of <code>x</code> for which the first expression produces infinity (because of overflow) but the second expression produces a finite result.<p>
<a name="238102"></a>
So, for example, the test program:<p>
<pre><a name="23224"></a>
class Test {
<a name="23225"></a>
	public static void main(String[] args) {
<a name="23226"></a>		double d = 8e+307;
<a name="23227"></a>		System.out.println(4.0 * d * 0.5);
<a name="23228"></a>		System.out.println(2.0 * d);
<a name="23229"></a>	}
<a name="23230"></a>}
</pre><a name="23231"></a>
prints:
<p><pre><a name="23232"></a>
Infinity
<a name="23233"></a>1.6e+308
</pre><a name="23234"></a>
because the first expression overflows and the second does not.
<p><a name="21009"></a>
In contrast, integer addition and multiplication <i>are</i> provably associative in Java; for example <code>a+b+c</code>, where <code>a</code>, <code>b</code>, and <code>c</code> are local variables (this simplifying assumption avoids issues involving multiple threads and <code>volatile</code> variables), will always produce the same answer whether evaluated as <code>(a+b)+c</code> or <code>a+(b+c)</code>; if the expression <code>b+c</code> occurs nearby in the code, a smart compiler may be able to use this common subexpression.<p>
<a name="23789"></a>
<h3>15.6.4    Argument Lists are Evaluated Left-to-Right</h3>
<a name="23790"></a>
In a method or constructor invocation or class instance creation expression, argument
expressions may appear within the parentheses, separated by commas. Each 
argument expression appears to be fully evaluated before any part of any argument 
expression to its right.
<p><a name="23791"></a>
Thus:<p>
<pre><a name="23792"></a>class Test {
</pre><pre><a name="50195"></a>
	public static void main(String[] args) {
<a name="23793"></a>		String s = "going, ";
<a name="23794"></a>		print3(s, s, s = "gone");
<a name="23795"></a>	}
<a name="23796"></a>
	static void print3(String a, String b, String c) {
<a name="23797"></a>		System.out.println(a + b + c);
<a name="23798"></a>	}
<a name="23799"></a>}
</pre><a name="23800"></a>
always prints:
<p><pre><a name="23801"></a>going, going, gone
</pre><a name="23802"></a>
because the assignment of the string <code>"gone"</code> to <code>s</code> occurs after the first two arguments
to <code>print3</code> have been evaluated.
<p><a name="23803"></a>
If evaluation of an argument expression completes abruptly, no part of any argument expression to its right appears to have been evaluated.<p>
<a name="23804"></a>
Thus, the example:<p>
<pre><a name="23805"></a>
class Test {
<a name="23806"></a>	static int id;
<a name="23807"></a>	public static void main(String[] args) {
<a name="23808"></a>		try {
<a name="23809"></a>			test(id = 1, oops(), id = 3);
<a name="23810"></a>		} catch (Exception e) {
<a name="23811"></a>			System.out.println(e + ", id=" + id);
<a name="23812"></a>		}
<a name="23813"></a>	}
<br><a name="23814"></a>	static int oops() throws Exception {
<a name="23815"></a>		throw new Exception("oops");
<a name="23816"></a>	}
<br><a name="23817"></a>	static int test(int a, int b, int c) {
<a name="23818"></a>		return a + b + c;
<a name="23819"></a>	}
<br><a name="23820"></a>}
</pre><a name="23821"></a>
prints:
<p><pre><a name="23822"></a>java.lang.Exception: oops, id=1
</pre><a name="23823"></a>
because the assignment of <code>3</code> to <code>id</code> is not executed.
<p><a name="23451"></a>
<h3>15.6.5    Evaluation Order for Other Expressions</h3>
<a name="23452"></a>
The order of evaluation for some expressions is not completely covered by these 
general rules, because these expressions may raise exceptional conditions at times 
that must be specified. See, specifically, the detailed explanations of evaluation 
order for the following kinds of expressions:
<p><ul><a name="23453"></a>
<li>class instance creation expressions <a href="15.doc.html#23745">(&#167;15.8.1)</a>
<a name="23469"></a>
<li>array creation expressions <a href="15.doc.html#23605">(&#167;15.9.1)</a>
<a name="23454"></a>
<li>method invocation expressions <a href="15.doc.html#45677">(&#167;15.11.4)</a>
<a name="23491"></a>
<li>array access expressions <a href="15.doc.html#23958">(&#167;15.12.1)</a>
<a name="240795"></a>
<li>assignments involving array components <a href="15.doc.html#5281">(&#167;15.25)</a>
</ul><a name="23302"></a>
<h2>15.7    Primary Expressions</h2>
<a name="36225"></a>
Primary expressions include most of the simplest kinds of expressions, from 
which all others are constructed: literals, field accesses, method invocations, and 
array accesses. A parenthesized expression is also treated syntactically as a primary
expression.
<p><ul><pre>
<i>Primary:<br>
</i>	<i>PrimaryNoNewArray<br>
</i>	<i>ArrayCreationExpression
</i>
<i>PrimaryNoNewArray:<br>
</i>	<i>Literal<br>
</i><code>	this<br>
</code>	<code>( </code><i>Expression</i><code> )<br>
</code>	<i>ClassInstanceCreationExpression<br>
</i>	<i>FieldAccess<br>
</i>	<i>MethodInvocation<br>
</i>	<i>ArrayAccess
</i></pre></ul><a name="236508"></a>
As programming language grammars go, this part of the Java grammar is unusual, in two ways. First, one might expect simple names, such as names of local variables and method parameters, to be primary expressions. For technical reasons, names are lumped together with primary expressions a little later when postfix expressions are introduced <a href="15.doc.html#36254">(&#167;15.13)</a>.<p>
<a name="19353"></a>
The technical reasons have to do with allowing left-to-right parsing of Java programs with only one-token lookahead. Consider the expressions <code>(z[3])</code> and <code>(z[])</code>. The first is a parenthesized array access <a href="15.doc.html#239587">(&#167;15.12)</a> and the second is the start of a cast <a href="15.doc.html#238146">(&#167;15.15)</a>. At the point that the look-ahead symbol is <code>[</code>, a left-to-right parse will have reduced the <code>z</code> to the nonterminal <i>Name</i>. In the context of a cast we prefer not to have to reduce the name to a <i>Primary</i>, but if <i>Name</i> were one of the alternatives for <i>Primary</i>, then we could not tell whether to do the reduction (that is, we could not determine whether the current situation would turn out to be a parenthesized array access or a cast) without looking ahead two tokens, to the token following the <code>[</code>. The Java grammar presented here avoids the problem by keeping <i>Name</i> and <i>Primary</i> separate and allowing either in certain other syntax rules (those for <i>MethodInvocation</i>, <i>ArrayAccess</i>, <i>PostfixExpression</i>, but not for <i>FieldAccess,</i> because this is covered by <i>Name</i>). This strategy effectively defers the question of whether a <i>Name</i> should be treated as a <i>Primary</i> until more context can be examined. (Other problems remain with cast expressions; see <a href="19.doc.html#44559">&#167;19.1.5</a>.)<p>
<a name="36318"></a>
The second unusual feature avoids a potential grammatical ambiguity in the expression:<p>
<pre><a name="36319"></a>new int[3][3]
</pre><a name="36320"></a>
which in Java always means a single creation of a multidimensional array, but 
which, without appropriate grammatical finesse, might also be interpreted as 
meaning the same as:
<p><pre><a name="36321"></a>(new int[3])[3]
</pre><a name="36322"></a>
This ambiguity is eliminated by splitting the expected definition of <i>Primary</i> into 
<i>Primary</i> and <i>PrimaryNoNewArray</i>. (This may be compared to the splitting of 
<i>Statement</i> into <i>Statement</i> and <i>StatementNoShortIf</i> <a href="14.doc.html#32584">(&#167;14.4)</a> to avoid the "dangling 
<code>else</code>" problem.)
<p><a name="224125"></a>
<h3>15.7.1    Literals</h3>
<a name="36407"></a>
A literal <a href="3.doc.html#48272">(&#167;3.10)</a> denotes a fixed, unchanging value.
<p><a name="36387"></a>
The following production from <a href="3.doc.html#48272">&#167;3.10</a> is repeated here for convenience:<p>
<ul><pre>
<i>Literal:<br>
	IntegerLiteral<br>
	FloatingPointLiteral<br>
	BooleanLiteral<br>
	CharacterLiteral<br>
	StringLiteral<br>
	NullLiteral
</i></pre></ul><a name="36400"></a>
The type of a literal is determined as follows:<p>
<ul><a name="43814"></a>
<li>The type of an integer literal that ends with <code>L</code> or <code>l</code> is <code>long</code>; the type of any other integer literal is <code>int</code>.
<a name="36413"></a>
<li>The type of a floating-point literal that ends with <code>F</code> or <code>f</code> is <code>float</code>; the type of any other floating-point literal is <code>double</code>.
<a name="36429"></a>
<li>The type of a boolean literal is <code>boolean</code>.
<a name="36436"></a>
<li>The type of a character literal is <code>char</code>.
<a name="36437"></a>
<li>The type of a string literal is <code>String</code>.
<a name="36411"></a>
<li>The type of the null literal <code>null</code> is the null type; its value is the null reference.
</ul><a name="36442"></a>
Evaluation of a literal always completes normally.<p>
<a name="31980"></a>
<h3>15.7.2    <code>this</code> </h3>
<a name="20069"></a>
The keyword <code>this</code> may be used only in the body of an instance method or constructor,
or in the initializer of an instance variable of a class. If it appears anywhere
else, a compile-time error occurs.
<p><a name="31983"></a>
When used as a primary expression, the keyword <code>this</code> denotes a value, that is a reference to the object for which the instance method was invoked <a href="15.doc.html#20448">(&#167;15.11)</a>, or to the object being constructed. The type of <code>this</code> is the class <i>C</i> within which the keyword <code>this</code> occurs. At run time, the class of the actual object referred to may be the class <i>C</i> or any subclass of <i>C</i>.<p>
<a name="31984"></a>
In the example:<p>
<pre><a name="31985"></a>
class IntVector {
<a name="20035"></a>	int[] v;
<a name="20033"></a>	boolean equals(IntVector other) {
<a name="20034"></a>		if (this == other)
<a name="43815"></a>			return true;
<a name="20048"></a>		if (v.length != other.v.length)
<a name="43816"></a>			return false;
<a name="20049"></a>		for (int i = 0; i &lt; v.length; i++)
<a name="20050"></a>			if (v[i] != other.v[i])
<a name="20051"></a>				return false;
<a name="20052"></a>		return true;
<a name="20053"></a>	}
<br><a name="20028"></a>}
</pre><a name="36469"></a>
the class <code>IntVector</code> implements a method <code>equals</code>, which compares two vectors. 
If the <code>other</code> vector is the same vector object as the one for which the <code>equals</code> 
method was invoked, then the check can skip the length and value comparisons. 
The <code>equals</code> method implements this check by comparing the reference to the 
<code>other</code> object to <code>this</code>.
<p><a name="20077"></a>
The keyword <code>this</code> is also used in a special explicit constructor invocation statement, which can appear at the beginning of a constructor body <a href="8.doc.html#78435">(&#167;8.6.5)</a>.<p>
<a name="236822"></a>
<h3>15.7.3    Parenthesized Expressions</h3>
<a name="236823"></a>
A parenthesized expression is a primary expression whose type is the type of the 
contained expression and whose value at run time is the value of the contained 
expression.
<p><a name="41147"></a>
<h2>15.8    Class Instance Creation Expressions</h2>
<a name="36595"></a>
A class instance creation expression is used to create new objects that are 
instances of classes.
<p><ul><pre>
<i>ClassInstanceCreationExpression:<br>
</i>	<code>new </code><i>ClassType</i><code> ( </code><i>ArgumentList</i><sub><i>opt</i></sub><code> )
</code>
<i>ArgumentList:<br>
</i>	<i>Expression<br>
</i>	<i>ArgumentList</i><code> , </code><i>Expression
</i></pre></ul><a name="224294"></a>
In a class instance creation expression, the <i>ClassType </i>must name a class that is not <code>abstract</code>. This class type is the type of the creation expression.<p>
<a name="224300"></a>
The arguments in the argument list, if any, are used to select a constructor declared in the body of the named class type, using the same matching rules as for method invocations <a href="15.doc.html#20448">(&#167;15.11)</a>. As in method invocations, a compile-time method matching error results if there is no unique constructor that is both applicable to the provided arguments and the most specific of all the applicable constructors.<p>
<a name="23745"></a>
<h3>15.8.1    Run-time Evaluation of Class Instance Creation Expressions</h3>
<a name="36655"></a>
At run time, evaluation of a class instance creation expression is as follows.
<p><a name="23746"></a>
First, space is allocated for the new class instance. If there is insufficient space to allocate the object, evaluation of the class instance creation expression completes abruptly by throwing an <code>OutOfMemoryError</code> <a href="15.doc.html#36687">(&#167;15.8.2)</a>.<p>
<a name="23753"></a>
The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its standard default value <a href="4.doc.html#10931">(&#167;4.5.4)</a>.<p>
<a name="36584"></a>
Next, the argument list is evaluated, left-to-right. If any of the argument evaluations completes abruptly, any argument expressions to its right are not evaluated, and the class instance creation expression completes abruptly for the same reason.<p>
<a name="36513"></a>
Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements <a href="8.doc.html#41652">(&#167;8.6)</a> and is described in detail in <a href="12.doc.html#44670">&#167;12.5</a>.<p>
<a name="23747"></a>
The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.<p>
<a name="36687"></a>
<h3>15.8.2    Example: Evaluation Order and Out-of-Memory Detection</h3>
<a name="36695"></a>
If evaluation of a class instance creation expression finds there is insufficient 
memory to perform the creation operation, then an <code>OutOfMemoryError</code> is thrown. 
This check occurs before any argument expressions are evaluated.
<p><a name="36696"></a>
So, for example, the test program:<p>
<pre><a name="36697"></a>
class List {
<a name="36776"></a>	int value;
<a name="36699"></a>	List next;
<a name="36700"></a>	static List head = new List(0);
<a name="36773"></a>	List(int n) { value = n; next = head; head = this; }
<a name="36701"></a>}
<a name="36702"></a>
class Test {
<a name="36703"></a>	public static void main(String[] args) {
<a name="36704"></a>		int id = 0, oldid = 0;
<a name="36706"></a>		try {
<a name="36841"></a>			for (;;) {
<a name="36707"></a>				++id;
<a name="36708"></a>				new List(oldid = id);
<a name="36847"></a>			}
<a name="36709"></a>		} catch (Error e) {
<a name="36710"></a>			System.out.println(e + ", " + (oldid==id));
<a name="36713"></a>		}
<a name="36714"></a>	}
<a name="36715"></a>}
</pre><a name="36716"></a>
prints:
<p><pre><a name="36787"></a>java.lang.OutOfMemoryError: List, false
</pre><a name="36788"></a>
because the out-or-memory condition is detected before the argument expression 
<code>oldid</code> <code>=</code> <code>id</code> is evaluated.
<p><a name="46163"></a>
Compare this to the treatment of array creation expressions <a href="15.doc.html#46168">(&#167;15.9)</a>, for which the out-of-memory condition is detected after evaluation of the dimension expressions <a href="15.doc.html#36736">(&#167;15.9.3)</a>.<p>
<a name="46168"></a>
<h2>15.9    Array Creation Expressions</h2>
<a name="46169"></a>
An array instance creation expression is used to create new arrays <a href="10.doc.html#27803">(&#167;10)</a>.
<p><ul><pre>
<i>ArrayCreationExpression:<br>
</i>	<code>new </code><i>PrimitiveType</i><code> </code><i>DimExprs</i><code> </code><i>Dims</i><sub><i>opt<br>
	</i></sub><code>new </code><i>TypeName</i><code> </code><i>DimExprs</i><code> </code><i>Dims</i><sub><i>opt
</i></sub>
<i>DimExprs:<br>
</i>	<i>DimExpr<br>
</i>	<i>DimExprs</i><code> </code><i>DimExpr
</i>
<i>DimExpr:<br>
</i>	<code>[ </code><i>Expression</i><code> ]
</code>
<i>Dims:<br>
</i>	<code>[ ]<br>
</code>	<i>Dims</i><code> [ ]
</code></pre></ul><a name="224310"></a>
An array creation expression creates an object that is a new array whose elements are of the type specified by the <i>PrimitiveType</i> or <i>TypeName</i>. The <i>TypeName</i> may name any reference type, even an <code>abstract</code> class type <a href="8.doc.html#34944">(&#167;8.1.2.1)</a> or an interface type <a href="9.doc.html#238678">(&#167;9)</a>.<p>
<a name="11508"></a>
The type of the creation expression is an array type that can denoted by a copy of the creation expression from which the <code>new</code> keyword and every <i>DimExpr</i> expression have been deleted; for example, the type of the creation expression:<p>
<pre><a name="224311"></a>new double[3][3][]
</pre><a name="224312"></a>
is:
<p><pre><a name="224313"></a>double[][][]
</pre><a name="23548"></a>
The type of each dimension expression <i>DimExpr</i> must be an integral type, or a compile-time error occurs. Each expression undergoes unary numeric promotion <a href="5.doc.html#170952">(&#167;5.6.1)</a>. The promoted type must be <code>int</code>, or a compile-time error occurs; this means, specifically, that the type of a dimension expression must not be <code>long</code>.<p>
<a name="23605"></a>
<h3>15.9.1    Run-time Evaluation of Array Creation Expressions</h3>
<a name="36668"></a>
At run time, evaluation of an array creation expression behaves as follows.
<p><a name="23552"></a>
First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated.<p>
<a name="23543"></a>
Next, the values of the dimension expressions are checked. If the value of any <i>DimExpr</i> expression is less than zero, then an <code>NegativeArraySizeException</code> is thrown.<p>
<a name="36922"></a>
Next, space is allocated for the new array. If there is insufficient space to allocate the array, evaluation of the array creation expression completes abruptly by throwing an <code>OutOfMemoryError</code>.<p>
<a name="23658"></a>
Then, if a single <i>DimExpr</i> appears, a single-dimensional array is created of the specified length, and each component of the array is initialized to its standard default value <a href="4.doc.html#10931">(&#167;4.5.4)</a>.<p>
<a name="23640"></a>
If an array creation expression contains <i>N</i> <i>DimExpr</i> expressions, then it effectively executes a set of nested loops of depth <img src="15.doc.anc7.gif"> to create the implied arrays of arrays. For example, the declaration:<p>
<pre><a name="23641"></a><code>float[][] matrix = new float[3][3];
</code></pre><a name="23642"></a>
is equivalent in behavior to:
<p><pre><a name="23643"></a>
float[][] matrix = new float[3][];
<a name="23644"></a>for (int <i>d</i> = 0; <i>d</i> &lt; matrix.length; <i>d</i>++)
<a name="50206"></a>	matrix[<i>d</i>] = new float[3];
</pre><a name="23645"></a>
and:
<p><pre><a name="23646"></a>Age[][][][][] Aquarius = new Age[6][10][8][12][];
</pre><a name="23647"></a>
is equivalent to:
<p><pre><a name="23648"></a>
Age[][][][][] Aquarius = new Age[6][][][][];
<a name="23649"></a>for (int <i>d1</i> = 0; <i>d1</i> &lt; Aquarius.length; <i>d1</i>++) {
<a name="237599"></a>	Aquarius[<i>d1</i>] = new Age[8][][][];
<a name="237600"></a>	for (int <i>d2</i> = 0; <i>d2</i> &lt; Aquarius[<i>d1</i>].length; <i>d2</i>++) {
<a name="237601"></a>		Aquarius[<i>d1</i>][<i>d2</i>] = new Age[10][][];
<a name="50214"></a>		for (int <i>d3</i> = 0; <i>d3</i> &lt; Aquarius[<i>d1</i>][<i>d2</i>].length; <i>d3</i>++) {
<a name="50216"></a>			Aquarius[<i>d1</i>][<i>d2</i>][<i>d3</i>] = new Age[12][];
<a name="50218"></a>		}
<a name="50220"></a>	}
<a name="50222"></a>}
</pre><a name="36995"></a>
with <i>d,</i> <i>d1</i>, <i>d2</i> and <i>d3</i> replaced by names that are not already locally declared. 
Thus, a single <code>new</code> expression actually creates one array of length 6, 6 arrays of 
length 10, <img src="15.doc.anc8.gif"> arrays of length 8, and <img src="15.doc.anc9.gif"> arrays of length 
12. This example leaves the fifth dimension, which would be arrays containing the 
actual array elements (references to <code>Age</code> objects), initialized only to null references.
These arrays can be filled in later by other code, such as:
<p><pre><a name="36991"></a>
Age[] Hair = { new Age("quartz"), new Age("topaz") };
<a name="36992"></a>Aquarius[1][9][6][9] = Hair;
</pre><a name="23652"></a>
A multidimensional array need not have arrays of the same length at each level; thus, a triangular matrix may be created by:<p>
<pre><a name="23653"></a>
float triang[][] = new float[100][];
<a name="23654"></a>for (int i = 0; i &lt; triang.length; i++)
<a name="50224"></a>	triang[i] = new float[i+1];
</pre><a name="23655"></a>
There is, however, no way to get this effect with a single creation expression.
<p><a name="23879"></a>
<h3>15.9.2    Example: Array Creation Evaluation Order</h3>
<a name="23883"></a>
In an array creation expression <a href="15.doc.html#46168">(&#167;15.9)</a>, there may be one or more dimension 
expressions, each within brackets. Each dimension expression is fully evaluated 
before any part of any dimension expression to its right.
<p><a name="23510"></a>
Thus:<p>
<pre><a name="23511"></a>
class Test {
<a name="23512"></a>	public static void main(String[] args) {
<a name="23513"></a>		int i = 4;
<a name="23514"></a>		int ia[][] = new int[i][i=3];
<a name="23515"></a>		System.out.println(
<a name="23516"></a>			"[" + ia.length + "," + ia[0].length + "]");
<a name="23517"></a>	}
<a name="23518"></a>}
</pre><a name="23519"></a>
prints:
<p><pre><a name="23520"></a>[4,3]
</pre><a name="23521"></a>
because the first dimension is calculated as <code>4</code> before the second dimension expression
sets <code>i</code> to <code>3</code>.
<p><a name="23522"></a>
If evaluation of a dimension expression completes abruptly, no part of any dimension expression to its right will appear to have been evaluated. Thus, the example: <p>
<pre><a name="23524"></a>
class Test {
<a name="23525"></a>
	public static void main(String[] args) {
<a name="23526"></a>		int[][] a = { { 00, 01 }, { 10, 11 } };
<a name="23527"></a>		int i = 99;
<a name="23528"></a>		try {
<a name="23529"></a>			a[val()][i = 1]++;
<a name="23530"></a>		} catch (Exception e) {
<a name="23531"></a>			System.out.println(e + ", i=" + i);
<a name="23532"></a>		}
<a name="23533"></a>	}
<br><a name="23534"></a>	static int val() throws Exception {
<a name="50226"></a>		throw new Exception("unimplemented");
<a name="50228"></a>	}
<br><a name="23535"></a>}
</pre><a name="23536"></a>
prints:
<p><pre><a name="23537"></a>java.lang.Exception: unimplemented, i=99
</pre><a name="23538"></a>
because the embedded assignment that sets <code>i</code> to <code>1</code> is never executed.
<p><a name="36736"></a>
<h3>15.9.3    Example: Array Creation and Out-of-Memory Detection</h3>
<a name="36885"></a>
If evaluation of an array creation expression finds there is insufficient memory to 
perform the creation operation, then an <code>OutOfMemoryError</code> is thrown. This check 
occurs only after evaluation of all dimension expressions has completed normally.
<p><a name="36744"></a>
So, for example, the test program:<p>
<pre><a name="36800"></a>
class Test {
<a name="36801"></a>	public static void main(String[] args) {
<a name="36802"></a>		int len = 0, oldlen = 0;
<a name="36818"></a>		Object[] a = new Object[0];
<a name="36804"></a>		try {
<a name="238115"></a>			for (;;) {
<a name="238116"></a>				++len;
<a name="238117"></a>				Object[] temp = new Object[oldlen = len];
<a name="238118"></a>				temp[0] = a;
<a name="36823"></a>				a = temp;
<a name="36833"></a>			}
<a name="36807"></a>		} catch (Error e) {
<a name="36808"></a>			System.out.println(e + ", " + (oldlen==len));
<a name="36811"></a>		}
<a name="36812"></a>	}
<a name="36813"></a>}
</pre><a name="36764"></a>
prints:
<p><pre><a name="36765"></a>java.lang.OutOfMemoryError, true
</pre><a name="36901"></a>
because the out-of-memory condition is detected after the argument expression 
<code>oldlen</code> = <code>len</code> is evaluated.
<p><a name="36905"></a>
Compare this to class instance creation expressions <a href="15.doc.html#41147">(&#167;15.8)</a>, which detect the out-of-memory condition before evaluating argument expressions <a href="15.doc.html#36687">(&#167;15.8.2)</a>.<p>
<a name="41267"></a>
<h2>15.10    Field Access Expressions</h2>
<a name="37024"></a>
A field access expression may access a field of an object or array, a reference to 
which is the value of either an expression or the special keyword <code>super</code>. (It is also 
possible to refer to a field of the current instance or current class by using a simple 
name; see <a href="15.doc.html#4984">&#167;15.13.1</a>.)
<p><ul><pre>
<i>FieldAccess:<br>
</i>	<i>Primary</i><code> . </code><i>Identifier<br>
</i>	<code>super . </code><i>Identifier
</i></pre></ul><a name="37051"></a>
The meaning of a field access expression is determined using the same rules as for qualified names <a href="6.doc.html#33916">(&#167;6.6)</a>, but limited by the fact that an expression cannot denote a package, class type, or interface type.<p>
<a name="37055"></a>
<h3>15.10.1    Field Access Using a Primary</h3>
<a name="37056"></a>
The type of the <i>Primary</i> must be a reference type <i>T</i>, or a compile-time error 
occurs. The meaning of the field access expression is determined as follows:
<p><ul><a name="20394"></a>
<li>If the identifier names several accessible member fields of type <i>T</i>, then the field access is ambiguous and a compile-time error occurs.
<a name="37075"></a>
<li>If the identifier does not name an accessible member field of type <i>T</i>, then the field access is undefined and a compile-time error occurs.
<a name="20398"></a>
<li>Otherwise, the identifier names a single accessible member field of type <i>T</i> and the type of the field access expression is the declared type of the field. At run time, the result of the field access expression is computed as follows:
<ul>
<a name="37316"></a>
<li>If the field is <code>static</code>:
<ul>
<a name="37335"></a>
<li>If the field is <code>final</code>, then the result is the value of the specified class variable in the class or interface that is the type of the <i>Primary</i> expression.
<a name="37336"></a>
<li>If the field is not <code>final</code>, then the result is a variable, namely, the specified class variable in the class that is the type of the <i>Primary</i> expression.
</ul>
<a name="37320"></a>
<li>If the field is not <code>static</code>:
<ul>
<a name="37110"></a>
<li>If the value of the <i>Primary</i> is <code>null</code>, then a <code>NullPointerException</code> is thrown.
<a name="20427"></a>
<li>If the field is <code>final</code>, then the result is the value of the specified instance variable in the object referenced by the value of the <i>Primary</i>.
<a name="20400"></a>
<li>If the field is not <code>final</code>, then the result is a variable, namely, the specified instance variable in the object referenced by the value of the <i>Primary</i>.
</ul>
</ul>
</ul><a name="37135"></a>
Note, specifically, that only the type of the <i>Primary</i> expression, not the class of the 
actual object referred to at run time, is used in determining which field to use.
<p><a name="21262"></a>
Thus, the example:<p>
<pre><a name="20890"></a>class S { int x = 0; }
<a name="20893"></a>class T extends S { int x = 1; }
<a name="20896"></a>class Test {
<a name="20897"></a>	public static void main(String[] args) {
</pre><pre><a name="20898"></a>
		T t = new T();
<a name="20899"></a>		System.out.println("t.x=" + t.x + when("t", t));
<a name="20928"></a>
		S s = new S();
<a name="20901"></a>		System.out.println("s.x=" + s.x + when("s", s));
<a name="20902"></a>
		s = t;
<a name="20916"></a>		System.out.println("s.x=" + s.x + when("s", s));
<br><a name="20904"></a>	}
<br><a name="20930"></a>
	static String when(String name, Object t) {
<a name="20931"></a>		return " when " + name + " holds a "
<a name="20959"></a>			+ t.getClass() + " at run time.";
<a name="20932"></a>	}
<a name="20905"></a>}
</pre><a name="20906"></a>
produces the output:
<p><pre><a name="20961"></a>
t.x=1 when t holds a class T at run time.
<a name="20962"></a>s.x=0 when s holds a class S at run time.
<a name="45445"></a>s.x=0 when s holds a class T at run time.
</pre><a name="45446"></a>
The last line shows that, indeed, the field that is accessed does not depend on the 
run-time class of the referenced object; even if <code>s</code> holds a reference to an object of 
class <code>T</code>, the expression <code>s.x</code> refers to the <code>x</code> field of class <code>S</code>, because the type of the 
expression <code>s</code> is <code>S</code>. Objects of class <code>T</code> contain two fields named <code>x</code>, one for class <code>T</code> 
and one for its superclass <code>S</code>.
<p><a name="22264"></a>
This lack of dynamic lookup for field accesses allows Java to run efficiently with straightforward implementations. The power of late binding and overriding is available in Java, but only when instance methods are used. Consider the same example using instance methods to access the fields:<p>
<pre><a name="37188"></a>class S { int x = 0; int z() { return x; } }
<a name="37189"></a>class T extends S { int x = 1; int z() { return x; } }
<a name="37190"></a>class Test {
</pre><pre><a name="37191"></a>
	public static void main(String[] args) {
<a name="37192"></a>		T t = new T();
<a name="37193"></a>		System.out.println("t.z()=" + t.z() + when("t", t));
<a name="37194"></a>		S s = new S();
<a name="37195"></a>		System.out.println("s.z()=" + s.z() + when("s", s));
<a name="37196"></a>		s = t;
<a name="37197"></a>		System.out.println("s.z()=" + s.z() + when("s", s));
<a name="37198"></a>	}
<a name="37199"></a>
	static String when(String name, Object t) {
<a name="37200"></a>		return " when " + name + " holds a "
<a name="37201"></a>			+ t.getClass() + " at run time.";
<a name="37202"></a>	}
<a name="37203"></a>}
</pre><a name="238134"></a>
Now the output is:
<p><pre><a name="37243"></a>
t.z()=1 when t holds a class T at run time.
<a name="37244"></a>s.z()=0 when s holds a class S at run time.
<a name="37245"></a>s.z()=1 when s holds a class T at run time.
</pre><a name="37254"></a>
The last line shows that, indeed, the method that is accessed <i>does</i> depend on the 
run-time class of referenced object; when <code>s</code> holds a reference to an object of class 
<code>T</code>, the expression <code>s.z()</code> refers to the <code>z</code> method of class <code>T</code>, despite the fact that the 
type of the expression <code>s</code> is <code>S</code>. Method <code>z</code> of class <code>T</code> overrides method <code>z</code> of class <code>S</code>.
<p><a name="22234"></a>
The following example demonstrates that a null reference may be used to access a class (<code>static</code>) variable without causing an exception:<p>
<pre><a name="37293"></a>
class Test {
<a name="37294"></a>	static String mountain = "Chocorua";
<a name="37295"></a>
	static Test favorite(){
<a name="37296"></a>		System.out.print("Mount ");
<a name="37297"></a>		return null;
<a name="37298"></a>	}
<a name="37299"></a>
	public static void main(String[] args) {
<a name="37300"></a>		System.out.println(favorite().mountain);
<a name="37301"></a>	}
<a name="37302"></a>}
</pre><a name="22242"></a>
It compiles, executes, and prints:
<p><pre><a name="22243"></a>Mount Chocorua
</pre><a name="39173"></a>
Even though the result of <code>favorite()</code> is <code>null</code>, a <code>NullPointerException</code> is <i>not</i> 
thrown. That "<code>Mount </code>" is printed demonstrates that the <i>Primary</i> expression is 
indeed fully evaluated at run time, despite the fact that only its type, not its value, 
is used to determine which field to access (because the field <code>mountain</code> is <code>static</code>).
<p><a name="20860"></a>
<h3>15.10.2    Accessing Superclass Members using <code>super</code></h3>
<a name="20451"></a>
The special form using the keyword <code>super</code> is valid only in an instance method or 
constructor, or in the initializer of an instance variable of a class; these are exactly 
the same situations in which the keyword <code>this</code> may be used <a href="15.doc.html#31980">(&#167;15.7.2)</a>. The form 
involving <code>super</code> may not be used anywhere in the class <code>Object</code>, since <code>Object</code> has 
no superclass; if <code>super</code> appears in class <code>Object</code>, then a compile-time error results.
<p><a name="37384"></a>
Suppose that a field access expression <code>super.</code><i>name</i> appears within class <i>C</i>, and the immediate superclass of <i>C</i> is class <i>S</i>. Then <code>super.</code><i>name</i> is treated exactly as if it had been the expression <code>((</code><i>S</i><code>)this).</code><i>name</i>; thus, it refers to the field named <i>name</i> of the current object, but with the current object viewed as an instance of the superclass. Thus it can access the field named <i>name</i> that is visible in class <i>S</i>, even if that field is hidden by a declaration of a field named <i>name</i> in class <i>C</i>.<p>
<a name="20763"></a>
The use of <code>super</code> is demonstrated by the following example:<p>
<pre><a name="20487"></a>
interface I { int x = 0; }
<a name="20490"></a>class T1 implements I { int x = 1; }
<a name="50230"></a>class T2 extends T1 { int x = 2; }
<a name="20497"></a>class T3 extends T2 {
<a name="20498"></a>	int x = 3;
<a name="20500"></a>	void test() {
<a name="20502"></a>		System.out.println("x=\t\t"+x);
<a name="20503"></a>		System.out.println("super.x=\t\t"+super.x);
<a name="20504"></a>		System.out.println("((T2)this).x=\t"+((T2)this).x);
<a name="20505"></a>		System.out.println("((T1)this).x=\t"+((T1)this).x);
<a name="20506"></a>		System.out.println("((I)this).x=\t"+((I)this).x);
<a name="20512"></a>	}
<a name="20513"></a>}
<a name="20514"></a>class Test {
<a name="20515"></a>	public static void main(String[] args) {
<a name="20516"></a>		new T3().test();
<a name="20518"></a>	}
<a name="20519"></a>}
</pre><a name="20520"></a>
which produces the output:
<p><pre><a name="20521"></a>
x=					3
<a name="20522"></a>super.x=					2
<a name="20523"></a>((T2)this).x=					2
<a name="20524"></a>((T1)this).x=					1
<a name="20525"></a>((I)this).x=					0
</pre><a name="37491"></a>
Within class <code>T3</code>, the expression <code>super.x</code> is treated exactly as if it were:
<p><pre><a name="37492"></a><code>((T2)this).x
</code></pre><a name="20448"></a>
<h2>15.11    Method Invocation Expressions</h2>
<a name="37518"></a>
A method invocation expression is used to invoke a class or instance method.
<p><ul><pre>
<i>MethodInvocation:<br>
</i>	<i>MethodName</i><code> ( </code><i>ArgumentList</i><sub><i>opt</i></sub><code> )<br>
</code>	<i>Primary</i><code> . </code><i>Identifier</i><code> ( </code><i>ArgumentList</i><sub><i>opt</i></sub><code> )<br>
	super . </code><i>Identifier</i><code> ( </code><i>ArgumentList</i><sub><i>opt</i></sub><code> )
</code></pre></ul><a name="8506"></a>
The definition of <i>ArgumentList</i> from <a href="15.doc.html#41147">&#167;15.8</a> is repeated here for convenience:
<p><ul><pre>
<i>ArgumentList:<br>
</i>	<i>Expression<br>
</i>	<i>ArgumentList</i><code> , </code><i>Expression
</i></pre></ul><a name="228339"></a>
Resolving a method name at compile time is more complicated than resolving a field name because of the possibility of method overloading. Invoking a method at run time is also more complicated than accessing a field because of the possibility of instance method overriding.<p>
<a name="38751"></a>
Determining the method that will be invoked by a method invocation expression involves several steps. The following three sections describe the compile-time processing of a method invocation; the determination of the type of the method invocation expression is described in <a href="15.doc.html#23617">&#167;15.11.3</a>.<p>
<a name="21692"></a>
<h3>15.11.1    Compile-Time Step 1: Determine Class or Interface to Search</h3>
<a name="37532"></a>
The first step in processing a method invocation at compile time is to figure out 
the name of the method to be invoked and which class or interface to check for 
definitions of methods of that name. There are several cases to consider, depending
on the form that precedes the left parenthesis, as follows:
<p><ul><a name="37552"></a>
<li>If the form is <i>MethodName</i>, then there are three subcases:
<ul>
<a name="37575"></a>
<li>If it is a simple name, that is, just an <i>Identifier</i>, then the name of the method is the <i>Identifier</i> and the class or interface to search is the one whose declaration contains the method invocation.
<a name="37556"></a>
<li>If it is a qualified name of the form <i>TypeName</i> <code>.</code> <i>Identifier</i>, then the name of the method is the <i>Identifier</i> and the class to search is the one named by the <i>TypeName</i>. If <i>TypeName</i> is the name of an interface rather than a class, then a compile-time error occurs, because this form can invoke only <code>static</code> methods and interfaces have no <code>static</code> methods.
<a name="37591"></a>
<li>In all other cases, the qualified name has the form <i>FieldName</i> <code>.</code> <i>Identifier</i>; then the name of the method is the <i>Identifier</i> and the class or interface to search is the declared type of the field named by the <i>FieldName</i>.
</ul>
<a name="37589"></a>
<li>If the form is <i>Primary</i> <code>.</code> <i>Identifier</i>, then the name of the method is the <i>Identifier</i> &#32;and the class or interface to be searched is the type of the <i>Primary</i> expression.
<a name="37600"></a>
<li>If the form is <code>super</code> <code>.</code> <i>Identifier</i>, then the name of the method is the <i>Identifier</i> and the class to be searched is the superclass of the class whose declaration contains the method invocation. A compile-time error occurs if such a method invocation occurs in an interface, or in the class <code>Object</code>, or in a <code>static</code> method, a static initializer, or the initializer for a <code>static</code> variable. It follows that a method invocation of this form may appear only in a class other than <code>Object</code>, and only in the body of an instance method, the body of a constructor, or an initializer for an instance variable.
</ul><a name="21693"></a>
<h3>15.11.2    Compile-Time Step 2: Determine Method Signature</h3>
<a name="19915"></a>
The second step searches the class or interface determined in the previous step for 
method declarations. This step uses the name of the method and the types of the 
argument expressions to locate method declarations that are both <i>applicable</i> and 
<i>accessible</i>, that is, declarations that can be correctly invoked on the given arguments.
There may be more than one such method declaration, in which case the 
<i>most specific</i> one is chosen. The descriptor (signature plus return type) of the most 
specific method declaration is one used at run time to do the method dispatch.
<p><a name="18427"></a>
<h4>15.11.2.1    Find Methods that are Applicable and Accessible</h4>
<a name="21818"></a>
A method declaration is <i>applicable</i> to a method invocation if and only if both of 
the following are true:
<p><ul><a name="37650"></a>
<li>The number of parameters in the method declaration equals the number of argument &#32;expressions in the method invocation.
<a name="37653"></a>
<li>The type of each actual argument can be converted by method invocation conversion <a href="5.doc.html#12687">(&#167;5.3)</a> to the type of the corresponding parameter. Method invocation conversion is the same as assignment conversion <a href="5.doc.html#170768">(&#167;5.2)</a>, except that constants of type <code>int</code> are never implicitly narrowed to <code>byte</code>, <code>short</code>, or <code>char</code>.
</ul><a name="21702"></a>
The class or interface determined by the process described in <a href="15.doc.html#21692">&#167;15.11.1</a> is searched for all method declarations applicable to this method invocation; method definitions inherited from superclasses and superinterfaces are included in this search.<p>
<a name="37690"></a>
Whether a method declaration is <i>accessible</i> to a method invocation depends on the access modifier (<code>public</code>, none, <code>protected</code>, or <code>private</code>) in the method declaration and on where the method invocation appears.<p>
<a name="37675"></a>
If the class or interface has no method declaration that is both applicable and accessible, then a compile-time error occurs.<p>
<a name="37720"></a>
In the example program:<p>
<pre><a name="37706"></a>
public class Doubler {
<a name="37707"></a>	static int two() { return two(1); }
<a name="37708"></a>	private static int two(int i) { return 2*i; }
<a name="37709"></a>}
<a name="37710"></a>
class Test extends Doubler {	
<a name="37733"></a>	public static long two(long j) {return j+j; }
<a name="37711"></a>
	public static void main(String[] args) {
<a name="37712"></a>		System.out.println(two(3));
<a name="37713"></a>		System.out.println(Doubler.two(3)); // compile-time error
<a name="37714"></a>	}
<a name="37715"></a>}
</pre><a name="37704"></a>
for the method invocation <code>two(1)</code> within class <code>Doubler</code>, there are two accessible 
methods named <code>two</code>, but only the second one is applicable, and so that is the one 
invoked at run time. For the method invocation <code>two(3)</code> within class <code>Test</code>, there 
are two applicable methods, but only the one in class <code>Test</code> is accessible, and so 
that is the one to be invoked at run time (the argument <code>3</code> is converted to type 
<code>long</code>). For the method invocation <code>Doubler.two(3)</code>, the class <code>Doubler</code>, not class 
<code>Test</code>, is searched for methods named <code>two</code>; the only applicable method is not 
accessible, and so this method invocation causes a compile-time error.
<p><a name="21942"></a>
Another example is:<p>
<pre><a name="21943"></a>
class ColoredPoint {
<a name="21949"></a>	int x, y;
<a name="21950"></a>	byte color;
<a name="21953"></a>	void setColor(byte color) { this.color = color; }
<a name="21954"></a>}
<a name="21955"></a>
class Test {
<a name="21956"></a>	public static void main(String[] args) {
<a name="21957"></a>		ColoredPoint cp = new ColoredPoint();
<a name="21958"></a>		byte color = 37;
<a name="21959"></a>		cp.setColor(color);
<a name="21960"></a>		cp.setColor(37);											// compile-time error
<a name="21961"></a>	}
<a name="21962"></a>}
</pre><a name="21881"></a>
Here, a compile-time error occurs for the second invocation of <code>setColor</code>, because 
no applicable method can be found at compile time. The type of the literal <code>37</code> is 
<code>int</code>, and <code>int</code> cannot be converted to <code>byte</code> by method invocation conversion. 
Assignment conversion, which is used in the initialization of the variable <code>color</code>, 
performs an implicit conversion of the constant from type <code>int</code> to <code>byte</code>, which is 
permitted because the value <code>37</code> is small enough to be represented in type <code>byte</code>; but 
such a conversion is not allowed for method invocation conversion.
<p><a name="21968"></a>
If the method <code>setColor</code> had, however, been declared to take an <code>int</code> instead of a <code>byte</code>, then both method invocations would be correct; the first invocation would be allowed because method invocation conversion does permit a widening conversion from <code>byte</code> to <code>int</code>. However, a narrowing cast would then be required in the body of <code>setColor</code>:<p>
<pre><a name="21973"></a>	void setColor(int color) { this.color = (byte)color; }
</pre><a name="18428"></a>
<h4>15.11.2.2    Choose the Most Specific Method</h4>
<a name="21703"></a>
If more than one method is both accessible and applicable to a method invocation, 
it is necessary to choose one to provide the descriptor for the run-time method dispatch.
Java uses the rule that the <i>most specific</i> method is chosen.
<p><a name="21708"></a>
The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.<p>
<a name="21709"></a>
The precise definition is as follows. Let <i>m</i> be a name and suppose that there are two declarations of methods named <i>m</i>, each having <i>n</i> parameters. Suppose that one declaration appears within a class or interface <i>T</i> and that the types of the parameters are <i>T1</i>,&#32;. . . ,&#32;<i>Tn</i>; suppose moreover that the other declaration appears within a class or interface <i>U</i> and that the types of the parameters are <i>U1</i>, . . . ,&#32;<i>Un</i>. Then the method <i>m</i> declared in <i>T</i> is <i>more specific</i> than the method <i>m</i> declared in <i>U</i><code></code> if and only if both of the following are true:<p>
<ul><a name="37872"></a>
<li><i>T</i> can be converted to <i>U</i><code></code> by method invocation conversion.
<a name="37876"></a>
<li><i>Tj</i> can be converted to <i>Uj</i><code></code> by method invocation conversion, for all <i>j</i> from <code>1</code> to <i>n</i>.
</ul><a name="37912"></a>
A method is said to be <i>maximally specific</i> for a method invocation if it is applicable and accessible and there is no other applicable and accessible method that is more specific.<p>
<a name="37937"></a>
If there is exactly one maximally specific method, then it is in fact <i>the most specific</i> method; it is necessarily more specific than any other method that is applicable and accessible. It is then subjected to some further compile-time checks as described in <a href="15.doc.html#23617">&#167;15.11.3</a>.<p>
<a name="37907"></a>
It is possible that no method is the most specific, because there are two or more maximally specific method declarations. In this case, we say that the method invocation is <i>ambiguous</i>, and a compile-time error occurs.<p>
<a name="21711"></a>
<h4>15.11.2.3    Example: Overloading Ambiguity</h4>
<a name="21712"></a>
Consider the example:
<p><pre><a name="21713"></a>class Point { int x, y; }
<a name="21714"></a>class ColoredPoint extends Point { int color; }
</pre><pre><a name="238137"></a>
class Test {
<a name="21716"></a>
	static void test(ColoredPoint p, Point q) {
<a name="21717"></a>		System.out.println("(ColoredPoint, Point)");
<a name="50239"></a>	}
<a name="21718"></a>
	static void test(Point p, ColoredPoint q) {
<a name="21719"></a>		System.out.println("(Point, ColoredPoint)");
<a name="50241"></a>	}
<a name="21720"></a>
	public static void main(String[] args) {
<a name="21722"></a>		ColoredPoint cp = new ColoredPoint();
<a name="21723"></a>		test(cp, cp);											// compile-time error
<a name="21724"></a>	}
<a name="21725"></a>}
</pre><a name="21726"></a>
This example produces an error at compile time. The problem is that there are two 
declarations of <code>test</code> that are applicable and accessible, and neither is more specific
than the other. Therefore, the method invocation is ambiguous.
<p><a name="38010"></a>
If a third definition of <code>test</code> were added:<p>
<pre><a name="38015"></a>
	static void test(ColoredPoint p, ColoredPoint q) {
<a name="38016"></a>		System.out.println("(ColoredPoint, ColoredPoint)");
<a name="38017"></a>	}
</pre><a name="38011"></a>
then it would be more specific than the other two, and the method invocation 
would no longer be ambiguous.
<p><a name="21727"></a>
<h4>15.11.2.4    Example: Return Type Not Considered</h4>
<a name="21728"></a>
As another example, consider:
<p><pre><a name="21729"></a>class Point { int x, y; }
<a name="21730"></a>class ColoredPoint extends Point { int color; }
<a name="21731"></a>class Test {
</pre><pre><a name="21732"></a>
	static int test(ColoredPoint p) {
<a name="21733"></a>		return color;
<a name="21734"></a>	}
<a name="21735"></a>
	static String test(Point p) {
<a name="21736"></a>		return "Point";
<a name="21737"></a>	}
<a name="21738"></a>
	public static void main(String[] args) {
<a name="21739"></a>		ColoredPoint cp = new ColoredPoint();
<a name="21740"></a>		String s = test(cp);											// compile-time error
<a name="21741"></a>	}
<a name="21742"></a>}
</pre><a name="21743"></a>
Here the most specific declaration of method <code>test</code> is the one taking a parameter 
of type <code>ColoredPoint</code>. Because the result type of the method is <code>int</code>, a compile-
time error occurs because an <code>int</code> cannot be converted to a <code>String</code> by assignment 
conversion. This example shows that, in Java, the result types of methods do not 
participate in resolving overloaded methods, so that the second <code>test</code> method, 
which returns a <code>String</code>, is not chosen, even though it has a result type that would 
allow the example program to compile without error.
<p><a name="29775"></a>
<h4>15.11.2.5    Example: Compile-Time Resolution</h4>
<a name="30681"></a>
The most applicable method is chosen at compile time; its descriptor determines 
what method is actually executed at run time. If a new method is added to a class, 
then Java code that was compiled with the old definition of the class might not use 
the new method, even if a recompilation would cause this method to be chosen.
<p><a name="30687"></a>
So, for example, consider two compilation units, one for class <code>Point</code>:<p>
<pre><a name="30688"></a>package points;
<a name="30689"></a>public class Point {
<a name="30718"></a>	public int x, y;
<a name="30706"></a>	public Point(int x, int y) { this.x = x; this.y = y; }
<a name="30774"></a>	public String toString() { return toString(""); }
</pre><pre><a name="30777"></a>
	public String toString(String s) {
<a name="30778"></a>		return "(" + x + "," + y + s + ")";
<a name="30779"></a>	}
<a name="30717"></a>}
</pre><a name="30799"></a>
and one for class <code>ColoredPoint</code>:
<p><pre><a name="30800"></a>package points;
<a name="30801"></a>public class ColoredPoint extends Point {
</pre><pre><a name="30802"></a>
	public static final int
<a name="30803"></a>		RED = 0, GREEN = 1, BLUE = 2;
<a name="30804"></a>
	public static String[] COLORS =
<a name="30805"></a>		{ "red", "green", "blue" };
<a name="30806"></a>	public byte color;
<a name="30807"></a>
	public ColoredPoint(int x, int y, int color) {
<a name="30808"></a>		super(x, y); this.color = (byte)color;
<a name="30809"></a>	}
<a name="38090"></a>
	/** Copy all relevant fields of the argument into
<a name="38091"></a>		 &#32; &#32;this <code>ColoredPoint</code> object. */
<a name="30810"></a>	public void adopt(Point p) { x = p.x; y = p.y; }
<a name="30811"></a>
	public String toString() {
<a name="30812"></a>		String s = "," + COLORS[color];
<a name="30813"></a>		return super.toString(s);
<a name="30814"></a>	}
<a name="38076"></a>}
</pre><a name="30815"></a>
Now consider a third compilation unit that uses <code>ColoredPoint</code>:
<p><pre><a name="30699"></a>import points.*;
<a name="30702"></a>class Test {
<a name="30700"></a>	public static void main(String[] args) {
<a name="30701"></a>		ColoredPoint cp =
<a name="30748"></a>			new ColoredPoint(6, 6, ColoredPoint.RED);
<a name="30722"></a>		ColoredPoint cp2 =
<a name="30751"></a>			new ColoredPoint(3, 3, ColoredPoint.GREEN);
<a name="30705"></a>		cp.adopt(cp2);
<a name="30766"></a>		System.out.println("cp: " + cp);
<a name="30720"></a>	}
<a name="30721"></a>}
</pre><a name="30754"></a>
The output is:
<p><pre><a name="30755"></a>cp: (3,3,red)
</pre><a name="30756"></a>
The application programmer who coded class <code>Test</code> has expected to see the word <code>green</code>, because the actual argument, a <code>ColoredPoint</code>, has a <code>color</code> field, and <code>color</code> would seem to be a "relevant field" (of course, the documentation for the package <code>Points</code> ought to have been much more precise!).<p>
<a name="38120"></a>
Notice, by the way, that the most specific method (indeed, the only applicable method) for the method invocation of <code>adopt</code> has a signature that indicates a method of one parameter, and the parameter is of type <code>Point</code>. This signature becomes part of the binary representation of class <code>Test</code> produced by the compiler and is used by the method invocation at run time.<p>
<a name="38098"></a>
Suppose the programmer reported this software error and the maintainer of the <code>points</code> package decided, after due deliberation, to correct it by adding a method to class <code>ColoredPoint</code>:<p>
<pre><a name="30827"></a>
public void adopt(ColoredPoint p) {
<a name="30828"></a>	adopt((Point)p); color = p.color;
<a name="30835"></a>}
</pre><a name="239516"></a>
If the application programmer then runs the old binary file for <code>Test</code> with the new binary file for <code>ColoredPoint</code>, the output is still:<p>
<pre><a name="38140"></a>cp: (3,3,red)
</pre><a name="38138"></a>
because the old binary file for <code>Test</code> still has the descriptor "one parameter, whose 
type is <code>Point</code>; <code>void</code>" associated with the method call <code>cp.adopt(cp2)</code>. If the 
source code for <code>Test</code> is recompiled, the compiler will then discover that there are 
now two applicable <code>adopt</code> methods, and that the signature for the more specific 
one is "one parameter, whose type is <code>ColoredPoint</code>; <code>void</code>"; running the program 
will then produce the desired output:
<p><pre><a name="38149"></a>cp: (3,3,green)
</pre><a name="30865"></a>
With forethought about such problems, the maintainer of the <code>points</code> package could fix the <code>ColoredPoint</code> class to work with both newly compiled and old code, by adding defensive code to the old <code>adopt</code> method for the sake of old code that still invokes it on <code>ColoredPoint</code> arguments:<p>
<pre><a name="30880"></a>
public void adopt(Point p) {
<a name="30886"></a>	if (p instanceof ColoredPoint)
<a name="30887"></a>		color = ((ColoredPoint)p).color;
<a name="30888"></a>	x = p.x; y = p.y;
<a name="30889"></a>}
</pre><a name="30914"></a>
A similar consideration applies if a method is to be moved from a class to a superclass. In this case a forwarding method can be left behind for the sake of old code. The maintainer of the <code>points</code> package might choose to move the <code>adopt</code> method that takes a <code>Point</code> argument up to class <code>Point</code>, so that all <code>Point</code> objects may enjoy the <code>adopt</code> functionality. To avoid compatibility problems with old binary code, the maintainer should leave a forwarding method behind in class <code>ColoredPoint</code>:<p>
<pre><a name="30926"></a>
public void adopt(Point p) {
<a name="30927"></a>	if (p instanceof ColoredPoint)
<a name="30928"></a>		color = ((ColoredPoint)p).color;
<a name="30929"></a>	super.adopt(p);
<a name="30930"></a>}
</pre><a name="38189"></a>
Ideally, Java code should be recompiled whenever code that it depends on is changed. However, in an environment where different Java classes are maintained by different organizations, this is not always feasible. Defensive programming with careful attention to the problems of class evolution can make upgraded code much more robust. See <a href="13.doc.html#44871">&#167;13</a> for a detailed discussion of binary compatibility and type evolution.<p>
<a name="23617"></a>
<h3>15.11.3    Compile-Time Step 3: Is the Chosen Method Appropriate?</h3>
<a name="23618"></a>
If there is a most specific method declaration for a method invocation, it is called 
the <i>compile-time declaration</i> for the method invocation. Two further checks must 
be made on the compile-time declaration:
<p><ul><a name="38457"></a>
<li>If the method invocation has, before the left parenthesis, a <i>MethodName</i> of the &#32;form <i>Identifier</i>, and the method invocation appears within a <code>static</code> method, a static initializer, or the initializer for a <code>static</code> variable, then the compile-time declaration must be <code>static</code>. If, instead, the compile-time declaration for the method invocation is for an instance method, then a compile-time error occurs. (The reason is that a method invocation of this form cannot be used to invoke an instance method in places where <code>this</code> <a href="15.doc.html#31980">(&#167;15.7.2)</a> is not defined.)
<a name="21464"></a>
<li>If the method invocation has, before the left parenthesis, a <i>MethodName</i> of the &#32;form <i>TypeName</i> <code>.</code> <i>Identifier</i>, then the compile-time declaration should be <code>static</code>. If the compile-time declaration for the method invocation is for an instance &#32;method, then a compile-time error occurs. (The reason is that a method invocation of this form does not specify a reference to an object that can serve as <code>this</code> within the instance method.)
<a name="21291"></a>
<li>If the compile-time declaration for the method invocation is <code>void</code>, then the method invocation must be a top-level expression, that is, the <i>Expression</i> in an expression statement <a href="14.doc.html#5984">(&#167;14.7)</a> or in the <i>ForInit</i> or <i>ForUpdate</i> part of a <code>for</code> statement <a href="14.doc.html#24588">(&#167;14.12)</a>, or a compile-time error occurs. (The reason is that such a method invocation produces no value and so must be used only in a situation where a value is not needed.)
</ul><a name="38703"></a>
The following compile-time information is then associated with the method invocation for use at run time:<p>
<ul><a name="38709"></a>
<li>The name of the method.
<a name="38704"></a>
<li>The class or interface that contains the compile-time declaration.
<a name="38716"></a>
<li>The number of parameters and the types of the parameters, in order.
<a name="38717"></a>
<li>The result type, or <code>void</code>, as declared in the compile-time declaration.
<a name="38712"></a>
<li>The invocation mode, computed as follows:
<ul>
<a name="38723"></a>
<li>If the compile-time declaration has the <code>static</code> modifier, then the invocation mode is <code>static</code>.
<a name="43892"></a>
<li>Otherwise, if the compile-time declaration has the <code>private</code> modifier, then the invocation mode is <code>nonvirtual</code>.
<a name="43894"></a>
<li>Otherwise, if the part of the method invocation before the left parenthesis is of the form <code>super</code> <code>.</code> <i>Identifier</i>, then the invocation mode is <code>super</code>.
<a name="38796"></a>
<li>Otherwise, if the compile-time declaration is in an interface, then the invocation mode is <code>interface</code>.
<a name="38732"></a>
<li>Otherwise, the invocation mode is <code>virtual</code>.
</ul>
</ul><a name="38220"></a>
If the compile-time declaration for the method invocation is not <code>void</code>, then the type of the method invocation expression is the result type specified in the compile-time declaration.<p>
<a name="45677"></a>
<h3>15.11.4    Runtime Evaluation of Method Invocation</h3>
<a name="45678"></a>
At run time, method invocation requires five steps. First, a <i>target reference</i> may be 
computed. Second, the argument expressions are evaluated. Third, the accessibility
of the method to be invoked is checked. Fourth, the actual code for the method 
to be executed is located. Fifth, a new activation frame is created, synchronization 
is performed if necessary, and control is transferred to the method code.
<p><a name="38359"></a>
<h4>15.11.4.1    Compute Target Reference (If Necessary)</h4>
<a name="38338"></a>
There are several cases to consider, depending on which of the three productions 
for <i>MethodInvocation</i> <a href="15.doc.html#20448">(&#167;15.11)</a> is involved:
<p><ul><a name="239420"></a>
<li>If the first production for <i>MethodInvocation</i>, which includes a <i>MethodName</i>, is involved, then there are three subcases:
<ul>
<a name="239421"></a>
<li>If the <i>MethodName</i> is a simple name, that is, just an <i>Identifier</i>, then there are two subcases:
<ul>
<a name="38362"></a>
<li>If the invocation mode is <code>static</code>, then there is no target reference.
<a name="38365"></a>
<li>Otherwise, the target reference is the value of <code>this</code>.
</ul>
<a name="38341"></a>
<li>If the <i>MethodName</i> is a qualified name of the form <i>TypeName</i> <code>.</code> <i>Identifier</i>, then there is no target reference.
<a name="38805"></a>
<li>If the <i>MethodName</i> is a qualified name of the form <i>FieldName</i> <code>.</code> <i>Identifier</i>, then there are two subcases:
<ul>
<a name="38806"></a>
<li>If the invocation mode is <code>static</code>, then there is no target reference.
<a name="38807"></a>
<li>Otherwise, the target reference is the value of the expression <i>FieldName</i>.
</ul>
</ul>
<a name="38815"></a>
<li>If the second production for <i>MethodInvocation</i>, which includes a <i>Primary</i>, is involved, then there are two subcases:
<ul>
<a name="38816"></a>
<li>If the invocation mode is <code>static</code>, then there is no target reference. The expression <i>Primary </i>is evaluated, but the result is then discarded.
<a name="38817"></a>
<li>Otherwise, the expression <i>Primary </i>is evaluated and the result is used as the target reference.
</ul>
</ul><ul><a name="38346"></a>
<br><br>In either case, if the evaluation of the <i>Primary</i> expression completes abruptly, then no part of any argument expression appears to have been evaluated, and the method invocation completes abruptly for the same reason.
</ul><ul><a name="38347"></a>
<li>If the third production for <i>MethodInvocation</i>, which includes the keyword <code>super</code>, is involved, then the target reference is the value of <code>this</code>.
</ul><a name="45449"></a>
<h4>15.11.4.2    Evaluate Arguments</h4>
<a name="21593"></a>
The argument expressions are evaluated in order, from left to right. If the evaluation
of any argument expression completes abruptly, then no part of any argument 
expression to its right appears to have been evaluated, and the method invocation 
completes abruptly for the same reason.
<p><a name="45453"></a>
<h4>15.11.4.3    Check Accessibility of Type and Method</h4>
<a name="38478"></a>
Let <i>C</i> be the class containing the method invocation, and let <i>T</i> be the class or interface
that contained the method being invoked, and <i>m</i> be the name of the method, 
as determined at compile time <a href="15.doc.html#23617">(&#167;15.11.3)</a>.
<p><a name="45463"></a>
A Java Virtual Machine must insure, as part of linkage, that the method <i>m</i> still exists in the type <i>T</i>. If this is not true, then a <code>NoSuchMethodError</code> (which is a subclass of <code>IncompatibleClassChangeError</code>) occurs. If the invocation mode is <code>interface</code>, then the virtual machine must also check that the target reference type still implements the specified interface. If the target reference type does not still implement the interface, then an <code>IncompatibleClassChangeError</code> occurs.<p>
<a name="45537"></a>
The virtual machine must also insure, during linkage, that the type <i>T</i> and the method <i>m</i> are accessible. For the type <i>T</i>:<p>
<ul><a name="45547"></a>
<li>If <i>T</i> is in the same package as <i>C</i>, then <i>T</i> is accessible.
<a name="45548"></a>
<li>If <i>T</i> is in a different package than <i>C</i>, and <i>T</i> is <code>public</code>, then <i>T</i> is accessible.
</ul><a name="239521"></a>
For the method <i>m</i>:
<p><ul><a name="45542"></a>
<li>If <i>m</i> is <code>public</code>, then <i>m</i> is accessible. (All members of interfaces are <code>public</code> <a href="9.doc.html#32392">(&#167;9.2)</a>).
<a name="45694"></a>
<li>If <i>m</i> is <code>protected</code>, then <i>m</i> is accessible if and only if either <i>T</i> is in the same package as <i>C</i>, or <i>C</i> is <i>T</i> or a subclass of <i>T</i>.
<a name="45695"></a>
<li>If <i>m</i> has default (package) access, then <i>m</i> is accessible if and only if <i>T</i> is in the same package as <i>C</i>.
<a name="45565"></a>
<li>If <i>m</i> is <code>private</code>, then <i>m</i> is accessible if and only if and <i>C</i> is <i>T</i>.
</ul><a name="45566"></a>
If either <i>T</i> or <i>m</i> is not accessible, then an <code>IllegalAccessError</code> occurs <a href="12.doc.html#44487">(&#167;12.3)</a>.
<p><a name="45606"></a>
<h4>15.11.4.4    Locate Method to Invoke</h4>
<a name="38785"></a>
The strategy for method lookup depends on the invocation mode.
<p><a name="45702"></a>
If the invocation mode is <code>static</code>, no target reference is needed and overriding is not allowed. Method <i>m</i> of class <i>T</i> is the one to be invoked.<p>
<a name="45395"></a>
Otherwise, an instance method is to be invoked and there is a target reference. If the target reference is <code>null</code>, a <code>NullPointerException</code> is thrown at this point. Otherwise, the target reference is said to refer to a <i>target object</i> and will be used as the value of the keyword <code>this</code> in the invoked method. The other four possibilities for the invocation mode are then considered.<p>
<a name="38856"></a>
If the invocation mode is <code>nonvirtual</code>, overriding is not allowed. Method <i>m</i> of class <i>T</i> is the one to be invoked.<p>
<a name="38864"></a>
Otherwise, the invocation mode is <code>interface</code>, <code>virtual</code>, or <code>super</code>, and overriding may occur. A <i>dynamic method lookup</i> is used. The dynamic lookup process starts from a class <i>S</i>, determined as follows:<p>
<ul><a name="45402"></a>
<li>If the invocation mode is <code>interface</code> or <code>virtual</code>, then <i>S</i> is initially the actual run-time class <i>R</i> of the target object. If the target object is an array, <i>R</i> is the class <code>Object</code>. (Note that for invocation mode <code>interface</code>, <i>R</i> necessarily implements <i>T</i>; for invocation mode <code>virtual</code>, <i>R</i> is necessarily either <i>T</i> or a subclass of <i>T</i>.)
<a name="45403"></a>
<li>If the invocation mode is <code>super</code>, then <i>S</i> is initially the superclass of the class <i>C</i> that contains the method invocation.
</ul><a name="39033"></a>
The dynamic method lookup uses the following procedure to search class <i>S</i>, and 
then the superclasses of class <i>S</i>, as necessary, for method <i>m</i>.
<p><ol>
<a name="38917"></a>
<li>If class <i>S</i> contains a declaration for a method named <i>m</i> with the same descriptor (same number of parameters, the same parameter types, and the same return type) required by the method invocation as determined at compile time <a href="15.doc.html#23617">(&#167;15.11.3)</a>, then this is the method to be invoked, and the procedure terminates. (We note that as part of the loading and linking process that the virtual machine checks that an overriding method is at least as accessible as the overridden method; an &#32;<code>IncompatibleClassChangeError</code> occurs if this is not the case.)
<a name="38959"></a>
<li>Otherwise, if <i>S</i> is not <i>T</i>, this same lookup procedure is performed using the superclass of <i>S</i>; whatever it comes up with is the result of this lookup.
</ol>
<a name="45627"></a>
This procedure will find a suitable method when it reaches class <code>T</code>, because otherwise
an <code>IllegalAccessError</code> would have been thrown by the checks of the previous
section <a href="15.doc.html#45453">&#167;15.11.4.3</a>.
<p><a name="45714"></a>
We note that the dynamic lookup process, while described here explicitly, will often be implemented implicitly, for example as a side-effect of the construction and use of per-class method dispatch tables, or the construction of other per-class structures used for efficient dispatch.<p>
<a name="39078"></a>
<h4>15.11.4.5    Create Frame, Synchronize, Transfer Control</h4>
<a name="39080"></a>
A method <i>m</i> in some class <i>S</i> has been identified as the one to be invoked.
<p><a name="39084"></a>
Now a new <i>activation frame</i> is created, containing the target reference (if any) and the argument values (if any), as well as enough space for the local variables and stack for the method to be invoked and any other bookkeeping information that may be required by the implementation (stack pointer, program counter, reference to previous activation frame, and the like). If there is not sufficient memory available to create such an activation frame, an <code>OutOfMemoryError</code> is thrown.<p>
<a name="39085"></a>
The newly created activation frame becomes the current activation frame. The effect of this is to assign the argument values to corresponding freshly created parameter variables of the method, and to make the target reference available as <code>this</code>, if there is a target reference.<p>
<a name="42183"></a>
If the method <i>m</i> is a <code>native</code> method but the necessary native, implementation-dependent binary code has not been loaded (<a href="javalang.doc15.html#52468">&#167;20.16.14</a>, <a href="javalang.doc15.html#30190">&#167;20.16.13</a>) or otherwise cannot be dynamically linked, then an <code>UnsatisfiedLinkError</code> is thrown.<p>
<a name="41731"></a>
If the method <i>m</i> is not <code>synchronized</code>, control is transferred to the body of the method <i>m</i> to be invoked.<p>
<a name="240503"></a>
If the method <i>m</i> is <code>synchronized</code>, then an object must be locked before the transfer of control. No further progress can be made until the current thread can obtain the lock. If there is a target reference, then the target must be locked; otherwise the <code>Class</code> object for class <i>S</i>, the class of the method <i>m</i>, must be locked. Control is then transferred to the body of the method <i>m</i> to be invoked. The object is automatically unlocked when execution of the body of the method has completed, whether normally or abruptly. The locking and unlocking behavior is exactly as if the body of the method were embedded in a <code>synchronized</code> statement <a href="14.doc.html#79287">(&#167;14.17)</a>.<p>
<a name="239532"></a>
<h4>15.11.4.6    Implementation Note: Combining Frames</h4>
<a name="39099"></a>
In order to allow certain kinds of code optimization, implementations are permitted
some freedom to combine activation frames. Suppose that a method invocation 
within class <i>C</i> is to invoke a method <i>m</i> within class <i>S</i>. Then the current activation 
frame may be used to provide space for <i>S</i> instead of creating a new activation 
frame only if one of the following conditions is true:
<p><ul><a name="39104"></a>
<li>Class <i>C</i> and class <i>S</i> have the same class loader <a href="javalang.doc13.html#14462">(&#167;20.14)</a> and class <i>S</i> is not <code>SecurityManager</code> or a subclass of <code>SecurityManager</code>.
<a name="39105"></a>
<li>Class <i>S</i> has no class loader (this fact indicates that it is a system class); class <i>S</i> is not <code>SecurityManager</code> or a subclass of <code>SecurityManager</code>; and method <i>m</i> is known not to call, directly or indirectly, any method of <code>SecurityManager</code> <a href="javalang.doc16.html#46274">(&#167;20.17)</a> or any of its subclasses.
</ul><a name="39122"></a>
<h4>15.11.4.7    Example: Target Reference and Static Methods</h4>
<a name="39148"></a>
When a target reference is computed and then discarded because the invocation 
mode is <code>static</code>, the reference is not examined to see whether it is <code>null</code>:
<p><pre><a name="39128"></a>
class Test {
<a name="240507"></a>	static void mountain() {<br>
		System.out.println("Monadnock");<br>
	}
<a name="39130"></a>
	static Test favorite(){
<a name="39131"></a>		System.out.print("Mount ");
<a name="39132"></a>		return null;
<a name="39133"></a>	}
<a name="39134"></a>
	public static void main(String[] args) {
<a name="39135"></a>		favorite().mountain();
<a name="39136"></a>	}
<a name="39137"></a>}
</pre><a name="39138"></a>
which prints:
<p><pre><a name="39139"></a>Mount Monadnock
</pre><a name="39140"></a>
Here <code>favorite</code> returns <code>null</code>, yet no <code>NullPointerException</code> is thrown.
<p><a name="23837"></a>
<h4>15.11.4.8    Example: Evaluation Order</h4>
<a name="23841"></a>
As part of an instance method invocation <a href="15.doc.html#20448">(&#167;15.11)</a>, there is an expression that 
denotes the object to be invoked. This expression appears to be fully evaluated 
before any part of any argument expression to the method invocation is evaluated.
<p><a name="23842"></a>
So, for example, in:<p>
<pre><a name="23843"></a>
class Test {
<a name="45454"></a>	public static void main(String[] args) {
<a name="23844"></a>		String s = "one";
<a name="23845"></a>		if (s.startsWith(s = "two"))
<a name="23846"></a>			System.out.println("oops");
<a name="23847"></a>	}
<a name="23848"></a>}
</pre><a name="239641"></a>
the occurrence of <code>s</code> before "<code>.startsWith</code>" is evaluated first, before the argument 
expression <code>s="two"</code>. Therefore, a reference to the string <code>"one"</code> is remembered as 
the target reference before the local variable s is changed to refer to the string 
<code>"two"</code>. As a result, the <code>startsWith</code> method <a href="javalang.doc11.html#2586">(&#167;20.12.20)</a> is invoked for target 
object <code>"one"</code> with argument <code>"two"</code>, so the result of the invocation is <code>false</code>, as the 
string <code>"one"</code> does not start with <code>"two"</code>. It follows that the test program does not 
print "<code>oops</code>".
<p><a name="239650"></a>
<h4>15.11.4.9    Example: Overriding</h4>
<a name="239651"></a>
In the example:
<p><pre><a name="239652"></a>
class Point {
<a name="239653"></a>
	final int EDGE = 20;
<a name="239654"></a>	int x, y;
<a name="239655"></a>
	void move(int dx, int dy) {
<a name="239656"></a>		x += dx; y += dy;
<a name="239657"></a>		if (Math.abs(x) &gt;= EDGE || Math.abs(y) &gt;= EDGE)
<a name="239658"></a>			clear();
<a name="239659"></a>	}
<a name="239660"></a>
	void clear() {
<a name="239661"></a>		System.out.println("\tPoint clear");
<a name="239662"></a>		x = 0; y = 0;
<a name="239663"></a>	}
<a name="239664"></a>}
<a name="239665"></a>
class ColoredPoint extends Point {
<a name="239666"></a>	int color;
</pre><pre><a name="239667"></a>
	void clear() {
<a name="239668"></a>		System.out.println("\tColoredPoint clear");
<a name="239669"></a>		super.clear();
<a name="239670"></a>		color = 0;
<a name="239671"></a>	}
<a name="239672"></a>}
</pre><a name="239673"></a>
the subclass <code>ColoredPoint</code> extends the <code>clear</code> abstraction defined by its superclass
<code>Point</code>. It does so by overriding the <code>clear</code> method with its own method, 
which invokes the <code>clear</code> method of its superclass, using the form <code>super.clear</code>.
<p><a name="239674"></a>
This method is then invoked whenever the target object for an invocation of <code>clear</code> is a <code>ColoredPoint</code>. Even the method <code>move</code> in <code>Point</code> invokes the <code>clear</code> method of class <code>ColoredPoint</code> when the class of <code>this</code> is <code>ColoredPoint</code>, as shown by the output of this test program:<p>
<pre><a name="239675"></a>
class Test {
<a name="239676"></a>	public static void main(String[] args) {
<a name="239677"></a>		Point p = new Point();
<a name="239678"></a>		System.out.println("p.move(20,20):");
<a name="239679"></a>		p.move(20, 20);
<a name="239680"></a>		ColoredPoint cp = new ColoredPoint();
<a name="239681"></a>		System.out.println("cp.move(20,20):");
<a name="239682"></a>		cp.move(20, 20);
<a name="239683"></a>		p = new ColoredPoint();
<a name="239684"></a>		System.out.println("p.move(20,20), p colored:");
<a name="239685"></a>		p.move(20, 20);
<a name="239686"></a>	}
<a name="239687"></a>}
</pre><a name="239688"></a>
which is:
<p><pre><a name="239689"></a>
p.move(20,20):
<a name="239690"></a>	Point clear
<a name="239691"></a>cp.move(20,20):
<a name="239692"></a>	ColoredPoint clear
<a name="239693"></a>	Point clear
<a name="239694"></a>p.move(20,20), p colored:
<a name="239695"></a>	ColoredPoint clear
<a name="239696"></a>	Point clear
</pre><a name="239749"></a>
Overriding is sometimes called "late-bound self-reference"; in this example it means that the reference to <code>clear</code> in the body of <code>Point.move</code> (which is really syntactic shorthand for <code>this.clear</code>) invokes a method chosen "late" (at run time, based on the run-time class of the object referenced by <code>this</code>) rather than a method chosen "early" (at compile time, based only on the type of <code>this</code>). This provides the Java programmer a powerful way of extending abstractions and is a key idea in object-oriented programming.<p>
<a name="239751"></a>
<h4>15.11.4.10    Example: Method Invocation using super</h4>
<a name="239647"></a>
An overridden instance method of a superclass may be accessed by using the keyword
<code>super</code> to access the members of the immediate superclass, bypassing any 
overriding declaration in the class that contains the method invocation.
<p><a name="39225"></a>
When accessing an instance variable, <code>super</code> means the same as a cast of <code>this</code> <a href="15.doc.html#20860">(&#167;15.10.2)</a>, but this equivalence does not hold true for method invocation. This is demonstrated by the example:<p>
<pre><a name="42566"></a>
class T1 {
<a name="42567"></a>	String s() { return "1"; }
<a name="42568"></a>}
<a name="39239"></a>
class T2 extends T1 {
<a name="42569"></a>	String s() { return "2"; }
<a name="42570"></a>}
<a name="42571"></a>
class T3 extends T2 {
<a name="42572"></a>	String s() { return "3"; }
<a name="42573"></a>
	void test() {
<a name="42574"></a>		System.out.println("s()=\t\t"+s());
<a name="42575"></a>		System.out.println("super.s()=\t"+super.s());
<a name="42576"></a>		System.out.print("((T2)this).s()=\t");
<a name="237215"></a>			System.out.println(((T2)this).s());
<a name="42577"></a>		System.out.print("((T1)this).s()=\t");
<a name="237216"></a>			System.out.println(((T1)this).s());
<a name="42578"></a>	}
<a name="42579"></a>}
<a name="42580"></a>
class Test {
<a name="42581"></a>	public static void main(String[] args) {
<a name="42582"></a>		T3 t3 = new T3();
<a name="42583"></a>		t3.test();
<a name="42584"></a>	}
<a name="42585"></a>}
</pre><a name="42586"></a>
which produces the output:
<p><pre><a name="42587"></a>
s()=					3
<a name="42588"></a>super.s()=					2
<a name="42589"></a>((T2)this).s()=					3
<a name="42590"></a>((T1)this).s()=					3
</pre><a name="239537"></a>
The casts to types <code>T1</code> and <code>T2</code> do not change the method that is invoked, because 
the instance method to be invoked is chosen according to the run-time class of the 
object referred to be <code>this</code>. A cast does not change the class of an object; it only 
checks that the class is compatible with the specified type.
<p><a name="239587"></a>
<h2>15.12    Array Access Expressions</h2>
<a name="39327"></a>
An array access expression refers to a variable that is a component of an array.
<p><ul><pre>
<i>ArrayAccess:<br>
</i>	<i>ExpressionName</i><code> [ </code><i>Expression</i><code> ]<br>
</code>	<i>PrimaryNoNewArray</i><code> [ </code><i>Expression</i><code> ]
</code></pre></ul><a name="19392"></a>
An array access expression contains two subexpressions, the <i>array reference expression</i> (before the left bracket) and the <i>index expression</i> (within the brackets). Note that the array reference expression may be a name or any primary expression that is not an array creation expression <a href="15.doc.html#46168">(&#167;15.9)</a>.<p>
<a name="22123"></a>
The type of the array reference expression must be an array type (call it <i>T</i><code>[]</code>, an array whose components are of type <i>T</i>) or a compile-time error results. Then the type of the array access expression is <i>T</i>.<p>
<a name="22103"></a>
The index expression undergoes unary numeric promotion <a href="5.doc.html#170952">(&#167;5.6.1)</a>; the promoted type must be <code>int</code>.<p>
<a name="23960"></a>
The result of an array reference is a variable of type <i>T</i>, namely the variable within the array selected by the value of the index expression. This resulting variable, which is a component of the array, is never considered <code>final</code>, even if the array reference was obtained from a <code>final</code> variable.<p>
<a name="23958"></a>
<h3>15.12.1    Runtime Evaluation of Array Access</h3>
<a name="39346"></a>
An array access expression is evaluated using the following procedure:
<p><ul><a name="22142"></a>
<li>First, the array reference expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason and the index expression is not evaluated.
<a name="22130"></a>
<li>Otherwise, the index expression is evaluated. If this evaluation completes abruptly, then the array access completes abruptly for the same reason.
<a name="22098"></a>
<li>Otherwise, if the value of the array reference expression is <code>null</code>, then a <code>NullPointerException</code> &#32;is thrown.
<a name="6936"></a>
<li>Otherwise, the value of the array reference expression indeed refers to an array. If the value of the index expression is less than zero, or greater than or equal to the array's length, then an <code>IndexOutOfBoundsException</code> is thrown.
<a name="6937"></a>
<li>Otherwise, the result of the array reference is the variable of type <i>T</i>, within the array, selected by the value of the index expression. (Note that this resulting variable, which is a component of the array, is never considered <code>final</code>, even if the array reference expression is a <code>final</code> variable.)
</ul><a name="23902"></a>
<h3>15.12.2    Examples: Array Access Evaluation Order</h3>
<a name="23906"></a>
In an array access, the expression to the left of the brackets appears to be fully 
evaluated before any part of the expression within the brackets is evaluated. For 
example, in the (admittedly monstrous) expression <code>a[(a=b)[3]]</code>, the expression 
<code>a</code> is fully evaluated before the expression <code>(a=b)[3]</code>; this means that the original 
value of <code>a</code> is fetched and remembered while the expression <code>(a=b)[3]</code> is evaluated.
This array referenced by the original value of <code>a</code> is then subscripted by a value 
that is element <code>3</code> of another array (possibly the same array) that was referenced by 
<code>b</code> and is now also referenced by <code>a</code>.
<p><a name="23907"></a>
Thus, the example:<p>
<pre><a name="23908"></a>
class Test {
<a name="23909"></a>	public static void main(String[] args) {
<a name="23910"></a>		int[] a = { 11, 12, 13, 14 };
<a name="23911"></a>		int[] b = { 0, 1, 2, 3 };
<a name="23912"></a>		System.out.println(a[(a=b)[3]]);
<a name="23913"></a>	}
<a name="23914"></a>}
</pre><a name="23915"></a>
prints:
<p><pre><a name="23916"></a>14
</pre><a name="23917"></a>
because the monstrous expression's value is equivalent to <code>a[b[3]]</code> or <code>a[3]</code> or <code>14</code>.
<p><a name="23918"></a>
If evaluation of the expression to the left of the brackets completes abruptly, no part of the expression within the brackets will appear to have been evaluated. Thus, the example:<p>
<pre><a name="23920"></a>
class Test {
<a name="23921"></a>	public static void main(String[] args) {
<a name="23922"></a>		int index = 1;
<a name="23923"></a>		try {
<a name="23924"></a>			skedaddle()[index=2]++;
<a name="23925"></a>		} catch (Exception e) {
<a name="23926"></a>			System.out.println(e + ", index=" + index);
<a name="23927"></a>		}
<a name="23928"></a>	}
<a name="23929"></a>	static int[] skedaddle() throws Exception {
<a name="50244"></a>		throw new Exception("Ciao");
<a name="50246"></a>	}
<a name="23930"></a>}
</pre><a name="23931"></a>
prints: 
<p><pre><a name="23932"></a>java.lang.Exception: Ciao, index=1
</pre><a name="23933"></a>
because the embedded assignment of <code>2</code> to <code>index</code> never occurs.
<p><a name="23937"></a>
If the array reference expression produces <code>null</code> instead of a reference to an array, then a <code>NullPointerException</code> is thrown at run time, but only after all parts of the array reference expression have been evaluated and only if these evaluations completed normally. Thus, the example:<p>
<pre><a name="23939"></a>
class Test {
<a name="23940"></a>
	public static void main(String[] args) {
<a name="23941"></a>		int index = 1;
<a name="23942"></a>		try {
<a name="23943"></a>			nada()[index=2]++;
<a name="23944"></a>		} catch (Exception e) {
<a name="23945"></a>			System.out.println(e + ", index=" + index);
<a name="23946"></a>		}
<a name="23947"></a>	}
<a name="23948"></a>	static int[] nada() { return null; }
<a name="23949"></a>}
</pre><a name="23950"></a>
prints:
<p><pre><a name="23951"></a>java.lang.NullPointerException, index=2
</pre><a name="23952"></a>
because the embedded assignment of <code>2</code> to <code>index</code> occurs before the check for a null 
pointer. As a related example, the program:
<p><pre><a name="36135"></a>
class Test {
<a name="36136"></a>
	public static void main(String[] args) {
<a name="36137"></a>		int[] a = null;
<a name="36138"></a>		try {
<a name="36139"></a>			int i = a[vamoose()];
<a name="36140"></a>			System.out.println(i);
<a name="36141"></a>		} catch (Exception e) {
<a name="36142"></a>			System.out.println(e);
<a name="36143"></a>		}
<a name="36144"></a>	}
<a name="36145"></a>
	static int vamoose() throws Exception {
<a name="36146"></a>		throw new Exception("Twenty-three skidoo!");
<a name="36147"></a>	}
<a name="36148"></a>}
</pre><a name="36149"></a>
always prints:
<p><pre><a name="36150"></a>java.lang.Exception: Twenty-three skidoo!
</pre><a name="36151"></a>
A <code>NullPointerException</code> never occurs, because the index expression must be 
completely evaluated before any part of the indexing operation occurs, and that 
includes the check as to whether the value of the left-hand operand is <code>null</code>.
<p><a name="36254"></a>
<h2>15.13    Postfix Expressions</h2>
<a name="39432"></a>
Postfix expressions include uses of the postfix <code>++</code> and <code>--</code> operators. Also, as discussed
in <a href="15.doc.html#23302">&#167;15.7</a>, names are not considered to be primary expressions, but are handled
separately in the grammar to avoid certain ambiguities. They become 
interchangeable only here, at the level of precedence of postfix expressions.
<p><ul><pre>
<i>PostfixExpression:<br>
	Primary<br>
	ExpressionName<br>
	PostIncrementExpression<br>
	PostDecrementExpression
</i></pre></ul><a name="4984"></a>
<h3>15.13.1    Names</h3>
<a name="41310"></a>
A name occurring in an expression may be, syntactically, an <i>ExpressionName</i> 
<a href="6.doc.html#20569">(&#167;6.5)</a>. The meaning of such an <i>ExpressionName</i> depends on its form:
<p><ul><a name="236664"></a>
<li>If it is a simple name, that is, just an <i>Identifier</i>, then there are two cases:
<ul>
<a name="237228"></a>
<li>If the <i>Identifier</i> occurs within the scope of a parameter or local variable named by that same <i>Identifier</i>, then the type of the <i>ExpressionName</i> is the declared type of the parameter or local variable; moreover, the value of the <i>ExpressionName</i> is a variable, namely, the parameter or local variable itself.
<a name="237229"></a>
<li>Otherwise, the <i>ExpressionName</i> is treated exactly as if it had been the field access expression <a href="15.doc.html#41267">(&#167;15.10)</a>:
</ul>
<a name="236761"></a><code>	 this.</code><i>Identifier
</i><ul>
<a name="236762"></a>
<li>containing the keyword <code>this</code> <a href="15.doc.html#31980">(&#167;15.7.2)</a>.
</ul>
<a name="237236"></a>
<li>Otherwise, if it is a qualified name of the form <i>PackageName</i> <code>.</code> <i>Identifier</i>, then a compile-time error occurs.
<a name="237240"></a>
<li>Otherwise, if it is a qualified name of the form <i>TypeName</i> <code>.</code> <i>Identifier</i>, then it is refers to a <code>static</code> field of the class or interface named by the <i>TypeName</i>. A compile-time error occurs if <i>TypeName</i> does not name a class or interface. A compile-time error occurs if the class or interface named by <i>TypeName</i> does not contain an accessible static field named by the <i>Identifier</i>. The type of the <i>ExpressionName</i> is the declared type of the <code>static</code> field. The value of the <i>ExpressionName</i> is a variable, namely, the <code>static</code> field itself.
<a name="236702"></a>
<li>Otherwise, it is a qualified name of the form <i>Ename</i> <code>.</code> <i>Identifier</i>, where <i>Ename</i> is itself an <i>ExpressionName</i>, and the <i>ExpressionName</i> is treated exactly as if it had been the field access expression <a href="15.doc.html#41267">(&#167;15.10)</a>:
<a name="236763"></a>	(<i>Ename</i>).<i>Identifier
</i></ul><ul><a name="236764"></a>
<br><br>containing a parenthesized expression <a href="15.doc.html#236822">(&#167;15.7.3)</a>.
</ul><a name="39438"></a>
<h3>15.13.2    Postfix Increment Operator <code>++</code></h3>
<ul><pre>
<i>PostIncrementExpression:<br>
</i>	<i>PostfixExpression</i><code> ++
</code></pre></ul><a name="40093"></a>
A postfix expression followed by a <code>++</code> operator is a postfix increment expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix increment expression is the type of the variable. The result of the postfix increment expression is not a variable, but a value.<p>
<a name="39658"></a>
At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value <code>1</code> is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion <a href="5.doc.html#170983">(&#167;5.6.2)</a> is performed on the value <code>1</code> and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion <a href="5.doc.html#175672">(&#167;5.1.3)</a> to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable <i>before </i>the new value is stored.<p>
<a name="41336"></a>
A variable that is declared <code>final</code> cannot be incremented, because when an access of a <code>final</code> variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix increment operator.<p>
<a name="4987"></a>
<h3>15.13.3    Postfix Decrement Operator <code>--</code></h3>
<ul><pre>
<i>PostDecrementExpression:<br>
</i>	<i>PostfixExpression</i><code> --
</code></pre></ul><a name="40094"></a>
A postfix expression followed by a <code>--</code> operator is a postfix decrement expression. The result of the postfix expression must be a variable of a numeric type, or a compile-time error occurs. The type of the postfix decrement expression is the type of the variable. The result of the postfix decrement expression is not a variable, but a value.<p>
<a name="39668"></a>
At run time, if evaluation of the operand expression completes abruptly, then the postfix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value <code>1</code> is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion <a href="5.doc.html#170983">(&#167;5.6.2)</a> is performed on the value <code>1</code> and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion <a href="5.doc.html#175672">(&#167;5.1.3)</a> to the type of the variable before it is stored. The value of the postfix decrement expression is the value of the variable <i>before </i>the new value is stored.<p>
<a name="41352"></a>
A variable that is declared <code>final</code> cannot be decremented, because when an access of a <code>final</code> variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a postfix decrement operator.<p>
<a name="4990"></a>
<h2>15.14    Unary Operators</h2>
<a name="31520"></a>
The <i>unary operators</i> include <code>+</code>, <code>-</code>, <code>++</code>, <code>--</code>, <code>~</code>, <code>!</code>, and cast operators. Expressions 
with unary operators group right-to-left, so that <code>-~x</code> means the same as <code>-(~x)</code>.
<p><ul><pre>
<i>UnaryExpression</i>:<br>
<code>	</code><i>PreIncrementExpression<br>
</i><code>	</code><i>PreDecrementExpression<br>
</i><code>	+ </code><i>UnaryExpression<br>
</i>	<code>- </code><i>UnaryExpression<br>
</i>	<i>UnaryExpressionNotPlusMinus
</i>
<i>PreIncrementExpression</i>:<br>
<code>	++ </code><i>UnaryExpression
</i>
<i>PreDecrementExpression</i>:<br>
	<code>-- </code><i>UnaryExpression
</i>
<i>UnaryExpressionNotPlusMinus</i><code>:<br>
	</code><i>PostfixExpression<br>
</i><code>	~ </code><i>UnaryExpression<br>
</i>	<code>! </code><i>UnaryExpression<br>
</i><code>	</code><i>CastExpression
</i></pre></ul><a name="29719"></a>
The following productions from <a href="15.doc.html#238146">&#167;15.15</a> are repeated here for convenience:
<p><ul><pre>
<i>CastExpression:<br>
</i><code>	( </code><i>PrimitiveType</i><code> ) </code><i>UnaryExpression<br>
</i><code>	( </code><i>ReferenceType</i><code> )&#32;</code><i>UnaryExpressionNotPlusMinus
</i></pre></ul><a name="22479"></a>
This portion of the Java grammar contains some tricks to avoid two potential syntactic ambiguities.<p>
<a name="22502"></a>
The first potential ambiguity would arise in expressions such as <code>(p)+q</code>, which looks, to a C or C++ programmer, as though it could be either be a cast to type <code>p</code> of a unary <code>+</code> operating on <code>q</code>, or a binary addition of two quantities <code>p</code> and <code>q</code>. In C and C++, the parser handles this problem by performing a limited amount of semantic analysis as it parses, so that it knows whether <code>p</code> is the name of a type or the name of a variable.<p>
<a name="39495"></a>
Java takes a different approach. The result of the <code>+</code> operator must be numeric, and all type names involved in casts on numeric values are known keywords. Thus, if <code>p</code> is a keyword naming a primitive type, then <code>(p)+q</code> can make sense only as a cast of a unary expression. However, if <code>p</code> is not a keyword naming a primitive type, then <code>(p)+q</code> can make sense only as a binary arithmetic operation. Similar remarks apply to the <code>-</code> operator. The grammar shown above splits <i>CastExpression</i> into two cases to make this distinction. The nonterminal <i>UnaryExpression </i>includes all unary operator, but the nonterminal <i>UnaryExpressionNotPlusMinus</i> excludes uses of all unary operators that could also be binary operators, which in Java are <code>+</code> and <code>-</code>.<p>
<a name="39551"></a>
The second potential ambiguity is that the expression <code>(p)++</code> could, to a C or C++ programmer, appear to be either a postfix increment of a parenthesized expression or the beginning of a cast, for example, in <code>(p)++q</code>. As before, parsers for C and C++ know whether <code>p</code> is the name of a type or the name of a variable. But a parser using only one-token lookahead and no semantic analysis during the parse would not be able to tell, when <code>++</code> is the lookahead token, whether <code>(p)</code> should be considered a <i>Primary</i> expression or left alone for later consideration as part of a <i>CastExpression</i>.<p>
<a name="39554"></a>
In Java, the result of the <code>++</code> operator must be numeric, and all type names involved in casts on numeric values are known keywords. Thus, if <code>p</code> is a keyword naming a primitive type, then <code>(p)++</code> can make sense only as a cast of a prefix increment expression, and there had better be an operand such as <code>q</code> following the <code>++</code>. However, if <code>p</code> is not a keyword naming a primitive type, then <code>(p)++</code> can make sense only as a postfix increment of <code>p</code>. Similar remarks apply to the <code>--</code> operator. The nonterminal <i>UnaryExpressionNotPlusMinus</i> therefore also excludes uses of the prefix operators <code>++</code> and <code>--</code>.<p>
<a name="39547"></a>
<h3>15.14.1    Prefix Increment Operator <code>++</code></h3>
<a name="5002"></a>
A unary expression preceded by a <code>++</code> operator is a prefix increment expression. 
The result of the unary expression must be a variable of a numeric type, or a compile-time
error occurs. The type of the prefix increment expression is the type of 
the variable. The result of the prefix increment expression is not a variable, but a 
value.
<p><a name="39621"></a>
At run time, if evaluation of the operand expression completes abruptly, then the prefix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value <code>1</code> is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion <a href="5.doc.html#170983">(&#167;5.6.2)</a> is performed on the value <code>1</code> and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion <a href="5.doc.html#175672">(&#167;5.1.3)</a> to the type of the variable before it is stored. The value of the prefix increment expression is the value of the variable <i>after </i>the new value is stored.<p>
<a name="239134"></a>
A variable that is declared <code>final</code> cannot be incremented, because when an access of a <code>final</code> variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix increment operator.<p>
<a name="239136"></a>
<h3>15.14.2    Prefix Decrement Operator <code>--</code></h3>
<a name="5005"></a>
A unary expression preceded by a <code>--</code> operator is a prefix decrement expression. 
The result of the unary expression must be a variable of a numeric type, or a compile-time
error occurs. The type of the prefix decrement expression is the type of 
the variable. The result of the prefix decrement expression is not a variable, but a 
value.
<p><a name="39634"></a>
At run time, if evaluation of the operand expression completes abruptly, then the prefix decrement expression completes abruptly for the same reason and no decrementation occurs. Otherwise, the value <code>1</code> is subtracted from the value of the variable and the difference is stored back into the variable. Before the subtraction, binary numeric promotion <a href="5.doc.html#170983">(&#167;5.6.2)</a> is performed on the value <code>1</code> and the value of the variable. If necessary, the difference is narrowed by a narrowing primitive conversion <a href="5.doc.html#175672">(&#167;5.1.3)</a> to the type of the variable before it is stored. The value of the prefix decrement expression is the value of the variable <i>after </i>the new value is stored.<p>
<a name="41323"></a>
A variable that is declared <code>final</code> cannot be decremented, because when an access of a <code>final</code> variable is used as an expression, the result is a value, not a variable. Thus, it cannot be used as the operand of a prefix decrement operator.<p>
<a name="24924"></a>
<h3>15.14.3    Unary Plus Operator <code>+</code></h3>
<a name="24926"></a>
The type of the operand expression of the unary <code>+</code> operator must be a primitive 
numeric type, or a compile-time error occurs. Unary numeric promotion <a href="5.doc.html#170952">(&#167;5.6.1)</a> 
is performed on the operand. The type of the unary plus expression is the promoted
type of the operand. The result of the unary plus expression is not a variable,
but a value, even if the result of the operand expression is a variable.
<p><a name="39701"></a>
At run time, the value of the unary plus expression is the promoted value of the operand.<p>
<a name="236345"></a>
<h3>15.14.4    Unary Minus Operator <code>-</code></h3>
<a name="39711"></a>
The type of the operand expression of the unary <code>-</code> operator must be a primitive 
numeric type, or a compile-time error occurs. Unary numeric promotion <a href="5.doc.html#170952">(&#167;5.6.1)</a> 
is performed on the operand. The type of the unary minus expression is the promoted
type of the operand.
<p><a name="39715"></a>
At run time, the value of the unary plus expression is the arithmetic negation of the promoted value of the operand.<p>
<a name="79921"></a>
For integer values, negation is the same as subtraction from zero. Java uses two's-complement representation for integers, and the range of two's-complement values is not symmetric, so negation of the maximum negative <code>int</code> or <code>long</code> results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown. For all integer values <code>x</code>, <code>-x</code> equals <code>(~x)+1</code>.<p>
<a name="5013"></a>
For floating-point values, negation is not the same as subtraction from zero, because if <code>x</code> is <code>+0.0</code>, then <code>0.0-x</code> equals <code>+0.0</code>, but <code>-x</code> equals <code>-0.0</code>. Unary minus merely inverts the sign of a floating-point number. Special cases of interest:<p>
<ul><a name="5014"></a>
<li>If the operand is NaN, the result is NaN (recall that NaN has no sign).
<a name="5015"></a>
<li>If the operand is an infinity, the result is the infinity of opposite sign.
<a name="5016"></a>
<li>If the operand is a zero, the result is the zero of opposite sign.
</ul><a name="5017"></a>
<h3>15.14.5    Bitwise Complement Operator <code>~</code></h3>
<a name="39739"></a>
The type of the operand expression of the unary <code>~</code> operator must be a primitive 
integral type, or a compile-time error occurs. Unary numeric promotion <a href="5.doc.html#170952">(&#167;5.6.1)</a> is 
performed on the operand. The type of the unary bitwise complement expression 
is the promoted type of the operand.
<p><a name="39743"></a>
At run time, the value of the unary bitwise complement expression is the bitwise complement of the promoted value of the operand; note that, in all cases, <code>~x</code> &#32;equals <code>(-x)-1</code>.<p>
<a name="13350"></a>
<h3>15.14.6    Logical Complement Operator <code>!</code></h3>
<a name="39767"></a>
The type of the operand expression of the unary <code>!</code> operator must be <code>boolean,</code> or a 
compile-time error occurs. The type of the unary logical complement expression 
is <code>boolean</code>.
<p><a name="39771"></a>
At run time, the value of the unary logical complement expression is <code>true</code> if the operand value is <code>false</code> and <code>false</code> if the operand value is <code>true</code>.<p>
<a name="238146"></a>
<h2>15.15    Cast Expressions</h2>
<a name="236464"></a>
A cast expression converts, at run time, a value of one numeric type to a similar 
value of another numeric type; or confirms, at compile time, that the type of an 
expression is <code>boolean</code>; or checks, at run time, that a reference value refers to an 
object whose class is compatible with a specified reference type.
<p><ul><pre>
<i>CastExpression:<br>
</i><code>	( </code><i>PrimitiveType</i><code> </code><i>Dims</i><sub><i>opt</i></sub><code> ) </code><i>UnaryExpression<br>
</i><code>	( </code><i>ReferenceType</i><code> ) </code><i>UnaryExpressionNotPlusMinus
</i></pre></ul><a name="39813"></a>
See <a href="15.doc.html#4990">&#167;15.14</a> for a discussion of the distinction between <i>UnaryExpression</i> and <i>UnaryExpressionNotPlusMinus</i>.<p>
<a name="39826"></a>
The type of a cast expression is the type whose name appears within the parentheses. (The parentheses and the type they contain are sometimes called the <i>cast operator</i>.) The result of a cast expression is not a variable, but a value, even if the result of the operand expression is a variable.<p>
<a name="39835"></a>
At run time, the operand value is converted by casting conversion <a href="5.doc.html#176921">(&#167;5.4)</a> to the type specified by the cast operator.<p>
<a name="239827"></a>
Not all casts are permitted by the Java language. Some casts result in an error at compile time. For example, a primitive value may not be cast to a reference type. Some casts can be proven, at compile time, always to be correct at run time. For example, it is always correct to convert a value of a class type to the type of its superclass; such a cast should require no special action at run time. Finally, some casts cannot be proven to be either always correct or always incorrect at compile time. Such casts require a test at run time. A <code>ClassCastException</code> is thrown if a cast is found at run time to be impermissible.<p>
<a name="239829"></a>
<h2>15.16    Multiplicative Operators</h2>
<a name="5029"></a>
The operators <code>*</code>, <code>/</code>, and <code>%</code> are called the <i>multiplicative operators</i>. They have the 
same precedence and are syntactically left-associative (they group left-to-right).
<p><ul><pre>
<i>MultiplicativeExpression:<br>
</i>	<i>UnaryExpression<br>
</i>	<i>MultiplicativeExpression</i><code> * </code><i>UnaryExpression<br>
</i>	<i>MultiplicativeExpression</i><code> / </code><i>UnaryExpression<br>
</i>	<i>MultiplicativeExpression</i><code> % </code><i>UnaryExpression
</i></pre></ul><a name="39873"></a>
The type of each of the operands of a multiplicative operator must be a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands <a href="5.doc.html#170983">(&#167;5.6.2)</a>. The type of a multiplicative expression is the promoted type of its operands. If this promoted type is <code>int</code> or <code>long</code>, then integer arithmetic is performed; if this promoted type is <code>float</code> or <code>double</code>, then floating-point arithmetic is performed.<p>
<a name="5036"></a>
<h3>15.16.1    Multiplication Operator <code>*</code></h3>
<a name="5037"></a>
The binary <code>*</code> operator performs multiplication, producing the product of its operands.
Multiplication is a commutative operation if the operand expressions have 
no side effects. While integer multiplication is associative when the operands are 
all of the same type, floating-point multiplication is not associative.
<p><a name="79991"></a>
If an integer multiplication overflows, then the result is the low-order bits of the mathematical product as represented in some sufficiently large two's-complement format. As a result, if overflow occurs, then the sign of the result may not be the same as the sign of the mathematical product of the two operand values.<p>
<a name="5039"></a>
The result of a floating-point multiplication is governed by the rules of IEEE 754 arithmetic:<p>
<ul><a name="5040"></a>
<li>If either operand is NaN, the result is NaN.
<a name="5041"></a>
<li>If the result is not NaN, the sign of the result is positive if both operands have the same sign, and negative if the operands have different signs.
<a name="24701"></a>
<li>Multiplication of an infinity by a zero results in NaN.
<a name="24702"></a>
<li>Multiplication of an infinity by a finite value results in a signed infinity. The sign is determined by the rule stated above.
<a name="5044"></a>
<li>In the remaining cases, where neither an infinity or NaN is involved, the product is computed. If the magnitude of the product is too large to represent, we say the operation overflows. The result is then an infinity of appropriate sign. If the magnitude is too small to represent, we say the operation underflows; the result is then a zero of appropriate sign. Otherwise, the product is rounded to the nearest representable value using IEEE 754 round-to-nearest mode. The Java language requires support of gradual underflow as defined by IEEE 754 <a href="4.doc.html#9249">(&#167;4.2.4)</a>.
</ul><a name="5045"></a>
Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a multiplication operator <code>*</code> never throws a run-time exception.<p>
<a name="5047"></a>
<h3>15.16.2    Division Operator <code>/</code></h3>
<a name="5048"></a>
The binary <code>/</code> operator performs division, producing the quotient of its operands. 
The left-hand operand is the dividend and the right-hand operand is the divisor.
<p><a name="45471"></a>
Integer division rounds toward <code>0</code>. That is, the quotient produced for operands <i>n</i> and <i>d</i> that are integers after binary numeric promotion <a href="5.doc.html#170983">(&#167;5.6.2)</a> is an integer value <i>q</i> whose magnitude is as large as possible while satisfying <img src="15.doc.anc4.gif">; moreover, <i>q </i>is positive when <img src="15.doc.anc5.gif">and <i>n</i> and <i>d</i> have the same sign, but <i>q</i> is negative when <img src="15.doc.anc6.gif">and <i>n</i> and <i>d </i>have opposite signs. There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is <code>-1</code>, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is <code>0</code>, then an <code>ArithmeticException</code> is thrown.<p>
<a name="45481"></a>
The result of a floating-point division is determined by the specification of IEEE arithmetic:<p>
<ul><a name="5054"></a>
<li>If either operand is NaN, the result is NaN.
<a name="5055"></a>
<li>If the result is not NaN, the sign of the result is positive if both operands have the same sign, negative if the operands have different signs.
<a name="5056"></a>
<li>Division of an infinity by an infinity results in NaN.
<a name="5057"></a>
<li>Division of an infinity by a finite value results in a signed infinity. The sign is determined by the rule stated above.
<a name="5058"></a>
<li>Division of a finite value by an infinity results in a signed zero. The sign is determined by the rule stated above.
<a name="236610"></a>
<li>Division of a zero by a zero results in NaN; division of zero by any other finite value results in a signed zero. The sign is determined by the rule stated above.
<a name="236611"></a>
<li>Division of a nonzero finite value by a zero results in a signed infinity. The sign is determined by the rule stated above.
<a name="236612"></a>
<li>In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the quotient is computed. If the magnitude of the quotient is too large to represent, we say the operation overflows; the result is then an infinity of appropriate sign. If the magnitude is too small to represent, we say the operation underflows and the result is then a zero of appropriate sign. Otherwise, the quotient is rounded to the nearest representable value using IEEE 754 round-to-nearest mode. The Java language requires support of gradual underflow as defined by IEEE 754 <a href="4.doc.html#9249">(&#167;4.2.4)</a>.
</ul><a name="5062"></a>
Despite the fact that overflow, underflow, division by zero, or loss of information may occur, evaluation of a floating-point division operator <code>/</code> never throws a run-time exception.<p>
<a name="24956"></a>
<h3>15.16.3    Remainder Operator <code>%</code></h3>
<a name="24958"></a>
The binary <code>%</code> operator is said to yield the remainder of its operands from an 
implied division; the left-hand operand is the dividend and the right-hand operand 
is the divisor.
<p><a name="40092"></a>
In C and C++, the remainder operator accepts only integral operands, but in Java, it also accepts floating-point operands.<p>
<a name="15723"></a>
The remainder operation for operands that are integers after binary numeric promotion <a href="5.doc.html#170983">(&#167;5.6.2)</a> produces a result value such that <code>(a/b)*b+(a%b)</code> is equal to <code>a</code>. This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is <code>-1</code> (the remainder is <code>0</code>). It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive; moreover, the magnitude of the result is always less than the magnitude of the divisor. If the value of the divisor for an integer remainder operator is <code>0</code>, then an <code>ArithmeticException</code> is thrown.<p>
<a name="40096"></a>
Examples:<p>
<pre><a name="40099"></a>
5%3 produces 2							(note that 5/3 produces 1)
<a name="40103"></a>5%(-3) produces 2							(note that 5/(-3) produces -1)
<a name="40107"></a>(-5)%3 produces -2							(note that (-5)/3 produces -1)
<a name="40111"></a>(-5)%(-3) produces -2							(note that (-5)/(-3) produces 1)
</pre><a name="5067"></a>
The result of a floating-point remainder operation as computed by the <code>%</code> operator is <i>not</i> the same as that produced by the remainder operation defined by IEEE 754. The IEEE 754 remainder operation computes the remainder from a rounding division, not a truncating division, and so its behavior is <i>not</i> analogous to that of the usual integer remainder operator. Instead, the Java language defines <code>%</code> on floating-point operations to behave in a manner analogous to that of the Java integer remainder operator; this may be compared with the C library function <code>fmod</code>. The IEEE 754 remainder operation may be computed by the Java library routine <code>Math.IEEEremainder</code> <a href="javalang.doc10.html#13956">(&#167;20.11.14)</a>.<p>
<a name="5068"></a>
The result of a Java floating-point remainder operation is determined by the rules of IEEE arithmetic:<p>
<ul><a name="5069"></a>
<li>If either operand is NaN, the result is NaN.
<a name="5070"></a>
<li>If the result is not NaN, the sign of the result equals the sign of the dividend.
<a name="5071"></a>
<li>If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
<a name="5072"></a>
<li>If the dividend is finite and the divisor is an infinity, the result equals the dividend.
<a name="5073"></a>
<li>If the dividend is a zero and the divisor is finite, the result equals the dividend.
<a name="5074"></a>
<li>In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder <i>r</i> from the division of a dividend <i>n</i> by a divisor <i>d</i> is defined by the mathematical relation <img src="15.doc.anc.gif"> where <i>q</i> is an integer that is negative only if <img src="15.doc.anc1.gif"> is negative and positive only if <img src="15.doc.anc2.gif"> is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of <i>n</i> and <i>d</i>.
</ul><a name="5084"></a>
Evaluation of a floating-point remainder operator <code>%</code> never throws a run-time exception, even if the right-hand operand is zero. Overflow, underflow, or loss of precision cannot occur.<p>
<a name="40146"></a>
Examples:<p>
<pre><a name="40147"></a>
5.0%3.0 produces 2.0
<a name="40148"></a>5.0%(-3.0) produces 2.0
<a name="40149"></a>(-5.0)%3.0 produces -2.0
<a name="40150"></a>(-5.0)%(-3.0) produces -2.0
</pre><a name="15746"></a>
<h2>15.17    Additive Operators</h2>
<a name="15749"></a>
The operators <code>+</code> and <code>-</code> are called the <i>additive operators</i>. They have the same precedence
and are syntactically left-associative (they group left-to-right).
<p><ul><pre>
<i>AdditiveExpression:<br>
</i>	<i>MultiplicativeExpression<br>
</i>	<i>AdditiveExpression</i><code> + </code><i>MultiplicativeExpression<br>
</i><code>	</code><i>AdditiveExpression</i><code> - </code><i>MultiplicativeExpression
</i></pre></ul><a name="39987"></a>
If the type of either operand of a + operator is <code>String</code>, then the operation is string concatenation.<p>
<a name="39998"></a>
Otherwise, the type of each of the operands of the <code>+</code> operator must be a primitive numeric type, or a compile-time error occurs. <p>
<a name="40002"></a>
In every case, the type of each of the operands of the binary <code>-</code> operator must be a primitive numeric type, or a compile-time error occurs. <p>
<a name="39990"></a>
<h3>15.17.1    String Concatenation Operator <code>+</code></h3>
<a name="7894"></a>
If only one operand expression is of type <code>String</code>, then string conversion is performed
on the other operand to produce a string at run time. The result is a reference
to a newly created <code>String</code> object that is the concatenation of the two 
operand strings. The characters of the left-hand operand precede the characters of 
the right-hand operand in the newly created string.
<p><a name="40220"></a>
<h4>15.17.1.1    String Conversion</h4>
<a name="40222"></a>
Any type may be converted to type <code>String</code> by <i>string conversion</i>.
<p><a name="22621"></a>
A value <i>x</i> of primitive type <i>T</i> is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression:<p>
<ul><a name="40316"></a>
<li>If <i>T</i> is <code>boolean</code>, then use <code>new</code> <code>Boolean(</code><i>x</i><code>)</code> <a href="javalang.doc3.html#14344">(&#167;20.4)</a>.
<a name="40320"></a>
<li>If <i>T</i> is <code>char</code>, then use <code>new</code> <code>Character(</code><i>x</i><code>)</code> <a href="javalang.doc4.html#14345">(&#167;20.5)</a>.
<a name="40265"></a>
<li>If <i>T</i> is <code>byte</code>, <code>short</code>, or <code>int</code>, then use <code>new</code> <code>Integer(</code><i>x</i><code>)</code> <a href="javalang.doc6.html#14348">(&#167;20.7)</a>.
<a name="40272"></a>
<li>If <i>T</i> is <code>long</code>, then use <code>new</code> <code>Long(</code><i>x</i><code>)</code> <a href="javalang.doc7.html#46750">(&#167;20.8)</a>.
<a name="40279"></a>
<li>If <i>T</i> is <code>float</code>, then use <code>new</code> <code>Float(</code><i>x</i><code>)</code> <a href="javalang.doc8.html#14394">(&#167;20.9)</a>.
<a name="40286"></a>
<li>If <i>T</i> is <code>double</code>, then use <code>new</code> <code>Double(</code><i>x</i><code>)</code> <a href="javalang.doc9.html#14390">(&#167;20.10)</a>.
</ul><a name="40362"></a>
This reference value is then converted to type <code>String</code> by string conversion.
<p><a name="22740"></a>
Now only reference values need to be considered. If the reference is <code>null</code>, it is converted to the string "<code>null</code>" (four ASCII characters <code>n</code>, <code>u</code>, <code>l</code>, <code>l</code>). Otherwise, the conversion is performed as if by an invocation of the <code>toString</code> method of the referenced object with no arguments; but if the result of invoking the <code>toString</code> method is <code>null</code>, then the string "<code>null</code>" is used instead. The <code>toString</code> method <a href="javalang.doc1.html#1152">(&#167;20.1.2)</a> is defined by the primordial class <code>Object</code> <a href="javalang.doc1.html#46442">(&#167;20.1)</a>; many classes override it, notably <code>Boolean</code>, <code>Character</code>, <code>Integer</code>, <code>Long</code>, <code>Float</code>, <code>Double,</code> and <code>String</code>.<p>
<a name="40226"></a>
<h4>15.17.1.2    Optimization of String Concatenation</h4>
<a name="40227"></a>
An implementation may choose to perform conversion and concatenation in one 
step to avoid creating and then discarding an intermediate <code>String</code> object. To 
increase the performance of repeated string concatenation, a Java compiler may 
use the <code>StringBuffer</code> class <a href="javalang.doc12.html#14461">(&#167;20.13)</a> or a similar technique to reduce the number 
of intermediate <code>String</code> objects that are created by evaluation of an expression.
<p><a name="22668"></a>
For primitive objects, an implementation may also optimize away the creation of a wrapper object by converting directly from a primitive type to a string.<p>
<a name="40423"></a>
<h4>15.17.1.3    Examples of String Concatenation</h4>
<a name="40221"></a>
The example expression:
<p><pre><a name="21340"></a>"The square root of 2 is " + Math.sqrt(2)
</pre><a name="21343"></a>
produces the result:
<p><pre><a name="40506"></a>"The square root of 2 is 1.4142135623730952"
</pre><a name="21344"></a>
The + operator is syntactically left-associative, no matter whether it is later determined by type analysis to represent string concatenation or addition. In some cases care is required to get the desired result. For example, the expression:<p>
<pre><a name="40517"></a>a + b + c
</pre><a name="40518"></a>
is always regarded as meaning:
<p><pre><a name="40519"></a>(a + b) + c
</pre><a name="40520"></a>
Therefore the result of the expression:
<p><pre><a name="40521"></a>1 + 2 + " fiddlers"
</pre><a name="40522"></a>
is:
<p><pre><a name="40523"></a>"3 fiddlers"
</pre><a name="40524"></a>
but the result of:
<p><pre><a name="40525"></a>"fiddlers " + 1 + 2
</pre><a name="40526"></a>
is:
<p><pre><a name="238151"></a>"fiddlers 12"
</pre><a name="238156"></a>
In this jocular little example:<p>
<pre><a name="238165"></a>
class Bottles {
<a name="40430"></a>
	static void printSong(Object stuff, int n) {
<a name="40431"></a>		String plural = "s";
<a name="40432"></a>		loop: while (true) {
<a name="40433"></a>			System.out.println(n + " bottle" + plural
<a name="40434"></a>				+ " of " + stuff + " on the wall,");
<a name="40435"></a>			System.out.println(n + " bottle" + plural
<a name="40436"></a>				+ " of " + stuff + ";");
<a name="40437"></a>			System.out.println("You take one down "
<a name="40451"></a>				+ "and pass it around:");
<a name="40438"></a>			--n;
<a name="40439"></a>			plural = (n == 1) ? "" : "s";
<a name="40440"></a>			if (n == 0)
<a name="40441"></a>				break loop;
<a name="40442"></a>			System.out.println(n + " bottle" + plural
<a name="40443"></a>				+ " of " + stuff + " on the wall!");
<a name="40444"></a>			System.out.println();
<a name="40445"></a>		}
<a name="40446"></a>		System.out.println("No bottles of " +
<a name="43970"></a>								stuff + " on the wall!");
<a name="40447"></a>	}
<br><a name="40448"></a>}
</pre><a name="40427"></a>
the method <code>printSong</code> will print a version of a children's song. Popular values 
for stuff include <code>"pop"</code> and <code>"beer"</code>; the most popular value for <code>n</code> is <code>100</code>. Here is 
the output that results from <code>Bottles.printSong("slime", 3)</code>:
<p><pre><a name="40461"></a>
3 bottles of slime on the wall,
<a name="40462"></a>3 bottles of slime;
<a name="40463"></a>You take one down and pass it around:
<a name="40464"></a>2 bottles of slime on the wall!
<a name="40465"></a>
<a name="40466"></a>2 bottles of slime on the wall,
<a name="40467"></a>2 bottles of slime;
<a name="40468"></a>You take one down and pass it around:
<a name="40469"></a>1 bottle of slime on the wall!
<a name="40470"></a>
<a name="40471"></a>1 bottle of slime on the wall,
<a name="40472"></a>1 bottle of slime;
<a name="40473"></a>You take one down and pass it around:
<a name="40474"></a>No bottles of slime on the wall!
</pre><a name="40459"></a>
In the code, note the careful conditional generation of the singular "<code>bottle</code>" when appropriate rather than the plural "<code>bottles</code>"; note also how the string concatenation operator was used to break the long constant string:<p>
<pre><a name="40479"></a>"You take one down and pass it around:"
</pre><a name="40485"></a>
into two pieces to avoid an inconveniently long line in the source code.
<p><a name="13510"></a>
<h3>15.17.2    Additive Operators (<code>+</code> and <code>-</code>) for Numeric Types</h3>
<a name="235182"></a>
The binary <code>+</code> operator performs addition when applied to two operands of numeric 
type, producing the sum of the operands. The binary <code>-</code> operator performs subtraction,
producing the difference of two numeric operands.
<p><a name="39970"></a>
Binary numeric promotion is performed on the operands <a href="5.doc.html#170983">(&#167;5.6.2)</a>. The type of an additive expression on numeric operands is the promoted type of its operands. If this promoted type is <code>int</code> or <code>long</code>, then integer arithmetic is performed; if this promoted type is <code>float</code> or <code>double</code>, then floating-point arithmetic is performed.<p>
<a name="39968"></a>
Addition is a commutative operation if the operand expressions have no side effects. Integer addition is associative when the operands are all of the same type, but floating-point addition is not associative.<p>
<a name="13512"></a>
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.<p>
<a name="13513"></a>
The result of a floating-point addition is determined using the following rules of IEEE arithmetic:<p>
<ul><a name="13514"></a>
<li>If either operand is NaN, the result is NaN.
<a name="13515"></a>
<li>The sum of two infinities of opposite sign is NaN.
<a name="13516"></a>
<li>The sum of two infinities of the same sign is the infinity of that sign.
<a name="13517"></a>
<li>The sum of an infinity and a finite value is equal to the infinite operand.
<a name="13518"></a>
<li>The sum of two zeros of opposite sign is positive zero.
<a name="13519"></a>
<li>The sum of two zeros of the same sign is the zero of that sign.
<a name="13520"></a>
<li>The sum of a zero and a nonzero finite value is equal to the nonzero operand.
<a name="13521"></a>
<li>The sum of two nonzero finite values of the same magnitude and opposite sign is positive zero.
<a name="13522"></a>
<li>In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, and the operands have the same sign or have different magnitudes, the sum is computed. If the magnitude of the sum is too large to represent, we say the operation overflows; the result is then an infinity of appropriate sign. If the magnitude is too small to represent, we say the operation underflows; the result is then a zero of appropriate sign. Otherwise, the sum is rounded to the nearest representable value using IEEE 754 round-to-nearest mode. The Java language requires support of gradual underflow as defined by IEEE 754 <a href="4.doc.html#9249">(&#167;4.2.4)</a>.
</ul><a name="13523"></a>
The binary <code>-</code> operator performs subtraction when applied to two operands of numeric type producing the difference of its operands; the left-hand operand is the minuend and the right-hand operand is the subtrahend. For both integer and floating-point subtraction, it is always the case that <code>a-b</code> produces the same result as <code>a+(-b)</code>. Note that, for integer values, subtraction from zero is the same as negation. However, for floating-point operands, subtraction from zero is <i>not</i> the same as negation, because if <code>x</code> is <code>+0.0</code>, then <code>0.0-x</code> equals <code>+0.0</code>, but <code>-x</code> equals <code>-0.0</code>. <p>
<a name="13524"></a>
Despite the fact that overflow, underflow, or loss of information may occur, evaluation of a numeric additive operator never throws a run-time exception.<p>
<a name="5121"></a>
<h2>15.18    Shift Operators</h2>
<a name="5122"></a>
The <i>shift operators</i> include left shift <code>&lt;&lt;</code>, signed right shift <code>&gt;&gt;</code>, and unsigned right 
shift <code>&gt;&gt;&gt;</code>; they are syntactically left-associative (they group left-to-right). The left-
hand operand of a shift operator is the value to be shifted; the right-hand operand 
specifies the shift distance.
<p><ul><pre>
<i>ShiftExpression:<br>
</i>	<i>AdditiveExpression<br>
</i>	<i>ShiftExpression</i><code> &lt;&lt; </code><i>AdditiveExpression<br>
</i>	<i>ShiftExpression</i><code> &gt;&gt; </code><i>AdditiveExpression<br>
</i>	<i>ShiftExpression</i><code> &gt;&gt;&gt; </code><i>AdditiveExpression
</i></pre></ul><a name="40554"></a>
The type of each of the operands of a shift operator must be a primitive integral type, or a compile-time error occurs. Binary numeric promotion <a href="5.doc.html#170983">(&#167;5.6.2)</a> is <i>not</i> performed on the operands; rather, unary numeric promotion <a href="5.doc.html#170952">(&#167;5.6.1)</a> is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.<p>
<a name="13680"></a>
If the promoted type of the left-hand operand is <code>int</code>, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator <code>&amp;</code> <a href="15.doc.html#5233">(&#167;15.21.1)</a> with the mask value <code>0x1f</code>. The shift distance actually used is therefore always in the range 0 to 31, inclusive.<p>
<a name="19183"></a>
If the promoted type of the left-hand operand is <code>long</code>, then only the six lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator <code>&amp;</code> <a href="15.doc.html#5233">(&#167;15.21.1)</a> with the mask value <code>0x3f</code>. The shift distance actually used is therefore always in the range 0 to 63, inclusive.<p>
<a name="19187"></a>
At run time, shift operations are performed on the two's complement integer representation of the value of the left operand.<p>
<a name="19188"></a>
The value of <code>n&lt;&lt;s</code> is <code>n</code> left-shifted <code>s</code> bit positions; this is equivalent (even if overflow occurs) to multiplication by two to the power <code>s</code>.<p>
<a name="5140"></a>
The value of <code>n&gt;&gt;s</code> is <code>n</code> right-shifted <code>s</code> bit positions with sign-extension. The resulting value is <img src="15.doc.anc3.gif">. For nonnegative values of <code>n</code>, this is equivalent to truncating integer division, as computed by the integer division operator <code>/</code>, by two to the power <code>s</code>.<p>
<a name="40638"></a>
The value of <code>n&gt;&gt;&gt;s</code> is <code>n</code> right-shifted <code>s</code> bit positions with zero-extension. If <code>n</code> is positive, then the result is the same as that of <code>n&gt;&gt;s</code>; if <code>n</code> is negative, the result is equal to that of the expression <code>(n&gt;&gt;s)+(2&lt;&lt;~s)</code> if the type of the left-hand operand is <code>int</code>, and to the result of the expression <code>(n&gt;&gt;s)+(2L&lt;&lt;~s)</code> if the type of the left-hand operand is <code>long</code>. The added term <code>(2&lt;&lt;~s)</code> or <code>(2L&lt;&lt;~s)</code> cancels out the propagated sign bit. (Note that, because of the implicit masking of the right-hand operand of a shift operator, <code>~s</code> as a shift distance is equivalent to <code>31-s</code> when shifting an <code>int</code> value and to <code>63-s</code> when shifting a <code>long</code> value.)<p>
<a name="40641"></a>
<h2>15.19    Relational Operators</h2>
<a name="139595"></a>
The <i>relational operators</i> are syntactically left-associative (they group left-to-
right), but this fact is not useful; for example, <code>a&lt;b&lt;c</code> parses as <code>(a&lt;b)&lt;c</code>, which is 
always a compile-time error, because the type of <code>a&lt;b</code> is always <code>boolean</code> and <code>&lt;</code> is 
not an operator on <code>boolean</code> values.
<p><ul><pre>
<i>RelationalExpression:<br>
</i>	<i>ShiftExpression<br>
</i>	<i>RelationalExpression</i><code> &lt; </code><i>ShiftExpression<br>
</i>	<i>RelationalExpression</i><code> &gt; </code><i>ShiftExpression<br>
</i>	<i>RelationalExpression</i><code> &lt;= </code><i>ShiftExpression<br>
</i>	<i>RelationalExpression</i><code> &gt;= </code><i>ShiftExpression<br>
</i>	<i>RelationalExpression</i><code> instanceof </code><i>ReferenceType
</i></pre></ul><a name="235261"></a>
The type of a relational expression is always <code>boolean</code>.
<p><a name="153654"></a>
<h3>15.19.1    Numerical Comparison Operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> </h3>
<a name="40647"></a>
The type of each of the operands of a numerical comparison operator must be a 
primitive numeric type, or a compile-time error occurs. Binary numeric promotion 
is performed on the operands <a href="5.doc.html#170983">(&#167;5.6.2)</a>. If the promoted type of the operands is <code>int</code> 
or <code>long</code>, then signed integer comparison is performed; if this promoted type is 
<code>float</code> or <code>double</code>, then floating-point comparison is performed.
<p><a name="5155"></a>
The result of a floating-point comparison, as determined by the specification of the IEEE 754 standard, is:<p>
<ul><a name="5156"></a>
<li>If either operand is NaN, then the result is <code>false</code>.
<a name="5157"></a>
<li>All values other than NaN are ordered, with negative infinity less than all finite values, and positive infinity greater than all finite values.
<a name="5158"></a>
<li>Positive zero and negative zero are considered equal. Therefore, <code>-0.0&lt;0.0</code> is <code>false</code>, for example, but <code>-0.0&lt;=0.0</code> is <code>true</code>. (Note, however, that the methods <code>Math.min</code> (<a href="javalang.doc10.html#13976">&#167;20.11.27</a>, <a href="javalang.doc10.html#13977">&#167;20.11.28</a>) and <code>Math.max</code> (<a href="javalang.doc10.html#6823">&#167;20.11.31</a>, <a href="javalang.doc10.html#6824">&#167;20.11.32</a>) treat negative zero as being strictly smaller than positive zero.)
</ul><a name="5159"></a>
Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:<p>
<ul><a name="5160"></a>
<li>The value produced by the <code>&lt;</code> operator is <code>true</code> if the value of the left-hand operand is less than the value of the right-hand operand, and otherwise is <code>false</code>.
<a name="5161"></a>
<li>The value produced by the <code>&lt;=</code> operator is <code>true</code> if the value of the left-hand operand is less than or equal to the value of the right-hand operand, and otherwise is <code>false</code>.
<a name="5162"></a>
<li>The value produced by the <code>&gt;</code> operator is <code>true</code> if the value of the left-hand operand is greater than the value of the right-hand operand, and otherwise is <code>false</code>.
<a name="5163"></a>
<li>The value produced by the <code>&gt;=</code> operator is <code>true</code> if the value of the left-hand operand is greater than or equal to the value of the right-hand operand, and otherwise is <code>false</code>.
</ul><a name="80289"></a>
<h3>15.19.2    Type Comparison Operator <code>instanceof</code></h3>
<a name="80291"></a>
The type of a <i>RelationalExpression</i> operand of the <code>instanceof</code> operator must be 
a reference type or the null type; otherwise, a compile-time error occurs. The <i>ReferenceType
</i> mentioned after the <code>instanceof</code> operator must denote a reference 
type; otherwise, a compile-time error occurs.
<p><a name="240816"></a>
At run time, the result of the <code>instanceof</code> operator is <code>true</code> if the value of the <i>RelationalExpression</i> is not <code>null</code> and the reference could be cast <a href="15.doc.html#238146">(&#167;15.15)</a> to the <i>ReferenceType</i> without raising a <code>ClassCastException</code>. Otherwise the result is <code>false</code>.<p>
<a name="19920"></a>
If a cast of the <i>RelationalExpression</i> to the <i>ReferenceType</i> would be rejected as a compile-time error, then the <code>instanceof</code> relational expression likewise produces a compile-time error. In such a situation, the result of the <code>instanceof</code> expression could never be <code>true</code>.<p>
<a name="238166"></a>
Consider the example program:<p>
<pre><a name="19921"></a>class Point { int x, y; }
<a name="22799"></a>class Element { int atomicNumber; }
<a name="238077"></a>class Test {
<a name="238078"></a>	public static void main(String[] args) {
<a name="238079"></a>		Point p = new Point();
<a name="22805"></a>		Element e = new Element();
<a name="22806"></a>		if (e instanceof Point) {											// compile-time error
<a name="22807"></a>			System.out.println("I get your point!");
<a name="22808"></a>			p = (Point)e;										// compile-time error
<a name="22809"></a>		}
<a name="22810"></a>	}
<a name="22811"></a>}
</pre><a name="22819"></a>
This example results in two compile-time errors. The cast <code>(Point)e</code> is incorrect 
because no instance of <code>Element</code> or any of its possible subclasses (none are shown 
here) could possibly be an instance of any subclass of <code>Point</code>. The <code>instanceof</code> 
expression is incorrect for exactly the same reason. If, on the other hand, the class 
<code>Point</code> were a subclass of <code>Element</code> (an admittedly strange notion in this example):
<p><pre><a name="40787"></a>class Point extends Element { int x, y; }
</pre><a name="40785"></a>
then the cast would be possible, though it would require a run-time check, and the 
<code>instanceof</code> expression would then be sensible and valid. The cast <code>(Point)e</code> 
would never raise an exception because it would not be executed if the value of <code>e</code> 
could not correctly be cast to type <code>Point</code>.
<p><a name="5192"></a>
<h2>15.20    Equality Operators</h2>
<a name="24723"></a>
The equality operators are syntactically left-associative (they group left-to-right), 
but this fact is essentially never useful; for example, <code>a==b==c</code> parses as 
<code>(a==b)==c</code>. The result type of <code>a==b</code> is always <code>boolean</code>, and <code>c</code> must therefore be 
of type <code>boolean</code> or a compile-time error occurs. Thus, <code>a==b==c</code> does <i>not</i> test to 
see whether <code>a</code>, <code>b</code>, and <code>c</code> are all equal.
<p><ul><pre>
<i>EqualityExpression:<br>
</i>	<i>RelationalExpression<br>
</i>	<i>EqualityExpression</i><code> == </code><i>RelationalExpression<br>
</i>	<i>EqualityExpression</i><code> != </code><i>RelationalExpression
</i></pre></ul><a name="5195"></a>
The == (equal to) and the != (not equal to) operators are analogous to the relational operators except for their lower precedence. Thus, <code>a&lt;b==c&lt;d</code> is <code>true</code> whenever <code>a&lt;b</code> and <code>c&lt;d</code> have the same truth value.<p>
<a name="5196"></a>
The equality operators may be used to compare two operands of numeric type, or two operands of type <code>boolean</code>, or two operands that are each of either reference type or the null type. All other cases result in a compile-time error. The type of an equality expression is always <code>boolean</code>.<p>
<a name="235280"></a>
In all cases, <code>a!=b</code> produces the same result as <code>!(a==b)</code>. The equality operators are commutative if the operand expressions have no side effects.<p>
<a name="5198"></a>
<h3>15.20.1    Numerical Equality Operators <code>==</code><code>&#32;</code>and <code>!=</code> </h3>
<a name="40803"></a>
If the operands of an equality operator are both of primitive numeric type, binary 
numeric promotion is performed on the operands <a href="5.doc.html#170983">(&#167;5.6.2)</a>. If the promoted type of 
the operands is <code>int</code> or <code>long</code>, then an integer equality test is performed; if the promoted
type is <code>float</code> or <code>double</code>, then a floating-point equality test is performed.
<p><a name="5203"></a>
Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:<p>
<ul><a name="5204"></a>
<li>If either operand is NaN, then the result of <code>==</code> is <code>false</code> but the result of <code>!=</code> is <code>true</code>. Indeed, the test <code>x!=x</code> is true if and only if the value of <code>x</code> is NaN. (The methods <code>Float.isNaN</code> <a href="javalang.doc8.html#1484">(&#167;20.9.19)</a> and <code>Double.isNaN</code> <a href="javalang.doc9.html#13852">(&#167;20.10.17)</a> may also be used to test whether a value is NaN.)
<a name="54500"></a>
<li>Positive zero and negative zero are considered equal. Therefore, <code>-0.0==0.0</code> is <code>true</code>, for example.
<a name="54501"></a>
<li>Otherwise, two distinct floating-point values are considered unequal by the equality operators. In particular, there is one value representing positive infinity and one value representing negative infinity; each compares equal only to itself, and each compares unequal to all other values.
</ul><a name="5207"></a>
Subject to these considerations for floating-point numbers, the following rules then hold for integer operands or for floating-point operands other than NaN:<p>
<ul><a name="5208"></a>
<li>The value produced by the <code>==</code> operator is <code>true</code> if the value of the left-hand operand is equal to the value of the right-hand operand; otherwise, the result is <code>false</code>.
<a name="236629"></a>
<li>The value produced by the <code>!=</code> operator is <code>true</code> if the value of the left-hand operand is not equal to the value of the right-hand operand; otherwise, the result is <code>false</code>.
</ul><a name="54508"></a>
<h3>15.20.2    Boolean Equality Operators <code>==</code><code>&#32;</code>and <code>!=</code> </h3>
<a name="80389"></a>
If the operands of an equality operator are both of type <code>boolean</code>, then the operation
is boolean equality. The <code>boolean</code> equality operators are associative.
<p><a name="5214"></a>
The result of <code>==</code> is <code>true</code> if the operands are both <code>true</code> or both <code>false</code>; otherwise, the result is <code>false</code>.<p>
<a name="5215"></a>
The result of <code>!=</code> is <code>false</code> if the operands are both <code>true</code> or both <code>false</code>; otherwise, the result is <code>true</code>. Thus <code>!=</code> behaves the same as <code>^</code> <a href="15.doc.html#5242">(&#167;15.21.2)</a> when applied to boolean operands.<p>
<a name="236163"></a>
<h3>15.20.3    Reference Equality Operators <code>==</code><code>&#32;</code>and <code>!=</code></h3>
<a name="236164"></a>
If the operands of an equality operator are both of either reference type or the null 
type, then the operation is object equality.
<p><a name="80399"></a>
A compile-time error occurs if it is impossible to convert the type of either operand to the type of the other by a casting conversion <a href="5.doc.html#176921">(&#167;5.4)</a>. The run-time values of the two operands would necessarily be unequal.<p>
<a name="5225"></a>
At run time, the result of <code>==</code> is <code>true</code> if the operand values are both <code>null</code> or both refer to the same object or array; otherwise, the result is <code>false</code>.<p>
<a name="5226"></a>
The result of <code>!=</code> is <code>false</code> if the operand values are both <code>null</code> or both refer to the same object or array; otherwise, the result is <code>true</code>.<p>
<a name="80417"></a>
While <code>==</code> may be used to compare references of type <code>String</code>, such an equality test determines whether or not the two operands refer to the same <code>String</code> object. The result is <code>false</code> if the operands are distinct <code>String</code> objects, even if they contain the same sequence of characters. The contents of two strings <code>s</code> and <code>t</code> can be tested for equality by the method invocation <code>s.equals(t)</code> <a href="javalang.doc14.html#29026">(&#167;20.12.9)</a>. See also <a href="3.doc.html#101083">&#167;3.10.5</a> and <a href="javalang.doc11.html#14026">&#167;20.12.47</a>.<p>
<a name="5228"></a>
<h2>15.21    Bitwise and Logical Operators</h2>
<a name="5229"></a>
The <i>bitwise</i> <i>operators</i> and <i>logical operators</i> include the AND operator <code>&amp;</code>, exclusive
OR operator <code>^</code>, and inclusive OR operator <code>|</code>. These operators have different 
precedence, with <code>&amp;</code> having the highest precedence and <code>|</code> the lowest precedence. 
Each of these operators is syntactically left-associative (each groups left-to-right). 
Each operator is commutative if the operand expressions have no side effects. 
Each operator is associative.
<p><ul><pre>
<i>AndExpression:<br>
</i>	<i>EqualityExpression<br>
</i>	<i>AndExpression</i><code> &amp; </code><i>EqualityExpression
</i>
<i>ExclusiveOrExpression:<br>
</i>	<i>AndExpression<br>
</i>	<i>ExclusiveOrExpression</i><code> ^ </code><i>AndExpression
</i>
<i>InclusiveOrExpression:<br>
</i>	<i>ExclusiveOrExpression<br>
</i>	<i>InclusiveOrExpression</i><code> | </code><i>ExclusiveOrExpression
</i></pre></ul><a name="40906"></a>
The bitwise and logical operators may be used to compare two operands of numeric type or two operands of type <code>boolean</code>. All other cases result in a compile-time error.<p>
<a name="5233"></a>
<h3>15.21.1    Integer Bitwise Operators <code>&amp;</code>, <code>^</code>, and <code>|</code></h3>
<a name="5234"></a>
When both operands of an operator <code>&amp;</code>, <code>^</code>, or <code>|</code> are of primitive integral type, binary 
numeric promotion is first performed on the operands <a href="5.doc.html#170983">(&#167;5.6.2)</a>. The type of the bitwise
operator expression is the promoted type of the operands.
<p><a name="5238"></a>
For <code>&amp;</code>, the result value is the bitwise AND of the operand values.<p>
<a name="5239"></a>
For <code>^</code>, the result value is the bitwise exclusive OR of the operand values.<p>
<a name="5240"></a>
For <code>|</code>, the result value is the bitwise inclusive OR of the operand values.<p>
<a name="40979"></a>
For example, the result of the expression <code>0xff00</code> <code>&amp;</code> <code>0xf0f0</code> is <code>0xf000</code>. The result of <code>0xff00</code> <code>^</code> <code>0xf0f0</code> is <code>0x0ff0</code>.The result of <code>0xff00</code> <code>|</code> <code>0xf0f0</code> is <code>0xfff0</code>.<p>
<a name="5242"></a>
<h3>15.21.2    Boolean Logical Operators <code>&amp;</code>, <code>^</code>, and <code>|</code></h3>
<a name="5243"></a>
When both operands of a <code>&amp;</code>, <code>^</code>, or <code>|</code> operator are of type <code>boolean</code>, then the type of 
the bitwise operator expression is <code>boolean</code>.
<p><a name="5244"></a>
For <code>&amp;</code>, the result value is <code>true</code> if both operand values are <code>true</code>; otherwise, the result is <code>false</code>.<p>
<a name="5245"></a>
For <code>^</code>, the result value is <code>true</code> if the operand values are different; otherwise, the result is <code>false</code>.<p>
<a name="5246"></a>
For <code>|</code>, the result value is <code>false</code> if both operand values are <code>false</code>; otherwise, the result is <code>true</code>.<p>
<a name="5247"></a>
<h2>15.22    Conditional-And Operator <code>&amp;&amp;</code></h2>
<a name="5248"></a>
The <code>&amp;&amp;</code> operator is like <code>&amp;</code> <a href="15.doc.html#5242">(&#167;15.21.2)</a>, but evaluates its right-hand operand only if 
the value of its left-hand operand is <code>true</code>. It is syntactically left-associative (it 
groups left-to-right). It is fully associative with respect to both side effects and 
result value; that is, for any expressions <i>a</i>, <i>b</i>, and <i>c</i>, evaluation of the expression 
<code>((</code><i>a</i><code>)&amp;&amp;(</code><i>b</i><code>))&amp;&amp;(</code><i>c</i><code>)</code> produces the same result, with the same side effects occurring
in the same order, as evaluation of the expression <code>(</code><i>a</i><code>)&amp;&amp;((</code><i>b</i><code>)&amp;&amp;(</code><i>c</i><code>))</code>.
<p><ul><pre>
<i>ConditionalAndExpression:<br>
</i>	<i>InclusiveOrExpression<br>
</i>	<i>ConditionalAndExpression</i><code> &amp;&amp; </code><i>InclusiveOrExpression
</i></pre></ul><a name="5251"></a>
Each operand of <code>&amp;&amp;</code> must be of type <code>boolean</code>, or a compile-time error occurs. The type of a conditional-and expression is always <code>boolean</code>.<p>
<a name="41086"></a>
At run time, the left-hand operand expression is evaluated first; if its value is <code>false</code>, the value of the conditional-and expression is <code>false</code> and the right-hand operand expression is not evaluated. If the value of the left-hand operand is <code>true</code>, then the right-hand expression is evaluated and its value becomes the value of the conditional-and expression. Thus, <code>&amp;&amp;</code> computes the same result as <code>&amp;</code> on <code>boolean</code> operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.<p>
<a name="54532"></a>
<h2>15.23    Conditional-Or Operator <code>||</code></h2>
<a name="41053"></a>
The <code>||</code> operator is like <code>|</code> <a href="15.doc.html#5242">(&#167;15.21.2)</a>, but evaluates its right-hand operand only if 
the value of its left-hand operand is <code>false</code>. It is syntactically left-associative (it 
groups left-to-right). It is fully associative with respect to both side effects and 
result value; that is, for any expressions <i>a</i>, <i>b</i>, and <i>c</i>, evaluation of the expression 
<code>((</code><i>a</i><code>)||(</code><i>b</i><code>))||(</code><i>c</i><code>)</code> produces the same result, with the same side effects occurring
in the same order, as evaluation of the expression <code>(</code><i>a</i><code>)||((</code><i>b</i><code>)||(</code><i>c</i><code>))</code>.
<p><ul><pre>
<i>ConditionalOrExpression:<br>
</i>	<i>ConditionalAndExpression<br>
</i>	<i>ConditionalOrExpression</i><code> || </code><i>ConditionalAndExpression
</i></pre></ul><a name="41088"></a>
Each operand of <code>||</code> must be of type <code>boolean,</code> or a compile-time error occurs. The type of a conditional-or expression is always <code>boolean</code>.<p>
<a name="41089"></a>
At run time, the left-hand operand expression is evaluated first; if its value is <code>true</code>, the value of the conditional-or expression is <code>true</code> and the right-hand operand expression is not evaluated. If the value of the left-hand operand is <code>false</code>, then the right-hand expression is evaluated and its value becomes the value of the conditional-or expression. Thus, <code>||</code> computes the same result as <code>|</code> on <code>boolean</code> operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.<p>
<a name="5257"></a>
<h2>15.24    Conditional Operator <code>?&#32;:</code></h2>
<a name="5258"></a>
The conditional operator <code>?&#32;:</code> uses the boolean value of one expression to decide 
which of two other expressions should be evaluated.
<p><a name="41113"></a>
The conditional operator is syntactically right-associative (it groups right-to-left), so that <code>a?b:c?d:e?f:g</code> means the same as <code>a?b:(c?d:(e?f:g))</code>.<p>
<ul><pre>
<i>ConditionalExpression:<br>
</i>	<i>ConditionalOrExpression<br>
</i>	<i>ConditionalOrExpression</i><code> ? </code><i>Expression</i><code> : </code><i>ConditionalExpression
</i></pre></ul><a name="236253"></a>
The conditional operator has three operand expressions; <code>?</code> appears between the first and second expressions, and <code>:</code> appears between the second and third expressions.<p>
<a name="40128"></a>
The first expression must be of type <code>boolean</code>, or a compile-time error occurs.<p>
<a name="40129"></a>
The conditional operator may be used to choose between second and third operands of numeric type, or second and third operands of type <code>boolean</code>, or second and third operands that are each of either reference type or the null type. All other cases result in a compile-time error.<p>
<a name="41144"></a>
Note that it is not permitted for either the second or the third operand expression to be an invocation of a <code>void</code> method. In fact, it is not permitted for a conditional expression to appear in any context where an invocation of a <code>void</code> method could appear <a href="14.doc.html#5984">(&#167;14.7)</a>.<p>
<a name="236267"></a>
The type of a conditional expression is determined as follows:<p>
<ul><a name="41198"></a>
<li>If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression.
<a name="236254"></a>
<li>Otherwise, if the second and third operands have numeric type, then there are several cases:
<ul>
<a name="5262"></a>
<li>If one of the operands is of type <code>byte</code> and the other is of type <code>short</code>, then the type of the conditional expression is <code>short</code>.
<a name="5264"></a>
<li>If one of the operands is of type <i>T</i><em></em> where <i>T</i><em></em> is <code>byte</code>, <code>short</code>, or <code>char</code>, and the other operand is a constant expression of type <code>int</code> whose value is representable in type <i>T</i>, then the type of the conditional expression is <i>T</i>.
<a name="5268"></a>
<li>Otherwise, binary numeric promotion <a href="5.doc.html#170983">(&#167;5.6.2)</a> is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
</ul>
<a name="5271"></a>
<li>If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type.
<a name="76547"></a>
<li>If the second and third operands are of different reference types, then it must be possible to convert one of the types to the other type (call this latter type <i>T</i>) by assignment conversion <a href="5.doc.html#170768">(&#167;5.2)</a>; the type of the conditional expression is <i>T</i>. It is a compile-time error if neither type is assignment compatible with the other type.
</ul><a name="40134"></a>
At run time, the first operand expression of the conditional expression is evaluated first; its <code>boolean</code> value is then used to choose either the second or the third operand expression:<p>
<ul><a name="5277"></a>
<li>If the value of the first operand is <code>true</code>, then the second operand expression is chosen.
<a name="5278"></a>
<li>If the value of the first operand is <code>false</code>, then the third operand expression is chosen.
</ul><a name="5279"></a>
The chosen operand expression is then evaluated and the resulting value is converted
to the type of the conditional expression as determined by the rules stated 
above. The operand expression not chosen is not evaluated for that particular evaluation
of the conditional expression.
<p><a name="5281"></a>
<h2>15.25    Assignment Operators</h2>
<a name="5282"></a>
There are 12 <i>assignment operators</i>; all are syntactically right-associative (they 
group right-to-left). Thus, <code>a=b=c</code> means <code>a=(b=c)</code>, which assigns the value of <code>c</code> to 
<code>b</code> and then assigns the value of <code>b</code> to <code>a</code>.
<p><ul><pre>
<i>AssignmentExpression:<br>
</i>	<i>ConditionalExpression<br>
</i>	<i>Assignment
</i>
<i>Assignment:<br>
</i>	<i>LeftHandSide</i><code> </code><i>AssignmentOperator</i><code> </code><i>AssignmentExpression
</i>
<i>LeftHandSide:<br>
</i>	<i>ExpressionName<br>
</i>	<i>FieldAccess<br>
</i>	<i>ArrayAccess
</i>
<i>AssignmentOperator:</i> <i>one</i> <i>of<br>
</i>	<code>=&#32;*=&#32;/=&#32;%=&#32;+=&#32;-=&#32;&lt;&lt;=&#32;&gt;&gt;=&#32;&gt;&gt;&gt;=&#32;&amp;=&#32;^=&#32;|=
</code></pre></ul><a name="236643"></a>
The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs. This operand may be a named variable, such as a local variable or a field of the current object or class, or it may be a computed variable, as can result from a field access <a href="15.doc.html#41267">(&#167;15.10)</a> or an array access <a href="15.doc.html#239587">(&#167;15.12)</a>. The type of the assignment expression is the type of the variable.<p>
<a name="41276"></a>
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.<p>
<a name="41365"></a>
A variable that is declared <code>final</code> cannot be assigned to, because when an access of a <code>final</code> variable is used as an expression, the result is a value, not a variable, and so it cannot be used as the operand of an assignment operator.<p>
<a name="5295"></a>
<h3>15.25.1    Simple Assignment Operator <code>=</code></h3>
<a name="22840"></a>
A compile-time error occurs if the type of the right-hand operand cannot be converted
to the type of the variable by assignment conversion <a href="5.doc.html#170768">(&#167;5.2)</a>.
<p><a name="41396"></a>
At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then three steps are required:<p>
<ul><a name="238369"></a>
<li>First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
<a name="238371"></a>
<li>Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="238384"></a>
<li>Otherwise, the value of the right-hand operand is converted to the type of the left-hand variable and the result of the conversion is stored into the variable.
</ul><a name="238191"></a>
If the left-hand operand expression is an array access expression <a href="15.doc.html#239587">(&#167;15.12)</a>, then 
many steps are required:
<p><ul><a name="238214"></a>
<li>First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
<a name="238234"></a>
<li>Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
<a name="238236"></a>
<li>Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="238216"></a>
<li>Otherwise, if the value of the array reference subexpression is <code>null</code>, then no assignment occurs and a <code>NullPointerException</code> &#32;is thrown.
<a name="238217"></a>
<li>Otherwise, the value of the array reference subexpression indeed refers to an array. If the value of the index subexpression is less than zero, or greater than &#32;or equal to the length of the array, then no assignment occurs and an <code>IndexOutOfBoundsException</code> &#32;is thrown.
<a name="238218"></a>
<li>Otherwise, the value of the index subexpression is used to select a component of the array referred to by the value of the array reference subexpression. This component is a variable; call its type <i>SC</i><i></i>. Also, let <i>TC</i> be the type of the left-hand operand of the assignment operator as determined at compile time.
<ul>
<a name="238255"></a>
<li>If <i>TC</i> is a primitive type, then <i>SC</i> is necessarily the same as <i>TC</i>. The value of the right-hand operand is converted to a value of type <i>TC</i> and stored into the selected array component.
<a name="238261"></a>
<li>If <i>T</i> is a reference type, then <i>SC</i> may not be the same as <i>T</i>, but rather a type that extends or implements <i>TC</i>. Let <i>RC</i> be the class of the object referred to by the value of the right-hand operand at run time.
<a name="238306"></a>
<li>The compiler may be able to prove at compile time that the array component will be of type <i>TC</i> exactly (for example, <i>TC</i> might be <code>final</code>). But if the compiler cannot prove at compile time that the array component will be of type <i>TC</i> exactly, then a check must be performed at run time to ensure that the class <i>RC</i> is assignment compatible <a href="5.doc.html#170768">(&#167;5.2)</a> with the actual type <i>SC</i> of the array component. This check is similar to a narrowing cast (<a href="5.doc.html#176921">&#167;5.4</a>, <a href="15.doc.html#238146">&#167;15.15</a>), except that if the check fails, an <code>ArrayStoreException</code> is thrown rather than a <code>ClassCastException</code>. Therefore:
<ul>
<a name="238321"></a>
<li>If class <i>RC</i> is not assignable to type <i>SC</i>, then no assignment occurs and an <code>ArrayStoreException</code> is thrown.
<a name="238334"></a>
<li>Otherwise, the reference value of the right-hand operand is stored into the selected array component.
</ul>
</ul>
</ul><a name="238526"></a>
The rules for assignment to an array component are illustrated by the following 
example program:
<p><pre><br><a name="238650"></a>class ArrayReferenceThrow extends RuntimeException { }
<br><br><a name="238651"></a>class IndexThrow extends RuntimeException { }
<br><br><a name="238652"></a>class RightHandSideThrow extends RuntimeException { }
<br></pre><pre><a name="238654"></a>
class IllustrateSimpleArrayAssignment {
<br><a name="238656"></a>	static Object[] objects = { new Object(), new Object() };
<br><br><a name="238657"></a>	static Thread[] threads = { new Thread(), new Thread() };
<br><a name="238658"></a>
	static Object[] arrayThrow() {
<a name="238738"></a>		throw new ArrayReferenceThrow();
<a name="238739"></a>	}
<br><br><a name="238659"></a>	static int indexThrow() { throw new IndexThrow(); }
<br><a name="238660"></a>
	static Thread rightThrow() {
<a name="238743"></a>		throw new RightHandSideThrow();
<a name="238744"></a>	}
<br><a name="238661"></a>
	static String name(Object q) {
<a name="238662"></a>		String sq = q.getClass().getName();
<a name="238663"></a>		int k = sq.lastIndexOf('.');
<a name="238664"></a>		return (k &lt; 0) ? sq : sq.substring(k+1);
<a name="238665"></a>	}
<br><a name="238666"></a>
	static void testFour(Object[] x, int j, Object y) {
<a name="238667"></a>		String sx = x == null ? "null" : name(x[0]) + "s";
<a name="238668"></a>		String sy = name(y);
<a name="238669"></a>		System.out.println();
<a name="238670"></a>		try {
<a name="238671"></a>			System.out.print(sx + "[throw]=throw =&gt; ");
<a name="238672"></a>			x[indexThrow()] = rightThrow();
<a name="238673"></a>			System.out.println("Okay!");
<a name="238674"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238675"></a>		try {
<a name="238676"></a>			System.out.print(sx + "[throw]=" + sy + " =&gt; ");
<a name="238677"></a>			x[indexThrow()] = y;
<a name="238678"></a>			System.out.println("Okay!");
<a name="238679"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238680"></a>		try {
<a name="238681"></a>			System.out.print(sx + "[" + j + "]=throw =&gt; ");
<a name="238682"></a>			x[j] = rightThrow();
<a name="238683"></a>			System.out.println("Okay!");
<a name="238684"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238685"></a>		try {
<a name="238686"></a>			System.out.print(sx + "[" + j + "]=" + sy + " =&gt; ");
<a name="238687"></a>			x[j] = y;
<a name="238688"></a>			System.out.println("Okay!");
<a name="238689"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238690"></a>	}
<br><a name="238691"></a>
	public static void main(String[] args) {
<a name="238692"></a>		try {
<a name="238693"></a>			System.out.print("throw[throw]=throw =&gt; ");
<a name="238694"></a>			arrayThrow()[indexThrow()] = rightThrow();
<a name="238695"></a>			System.out.println("Okay!");
<a name="238696"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238697"></a>		try {
<a name="238698"></a>			System.out.print("throw[throw]=Thread =&gt; ");
<a name="238699"></a>			arrayThrow()[indexThrow()] = new Thread();
<a name="238700"></a>			System.out.println("Okay!");
<a name="238701"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238702"></a>		try {
<a name="238703"></a>			System.out.print("throw[1]=throw =&gt; ");
<a name="238704"></a>			arrayThrow()[1] = rightThrow();
<a name="238705"></a>			System.out.println("Okay!");
<a name="238706"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238707"></a>		try {
<a name="238708"></a>			System.out.print("throw[1]=Thread =&gt; ");
<a name="238709"></a>			arrayThrow()[1] = new Thread();
<a name="238710"></a>			System.out.println("Okay!");
<a name="238711"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238712"></a>
		testFour(null, 1, new StringBuffer());
<a name="238713"></a>		testFour(null, 1, new StringBuffer());
<a name="238714"></a>		testFour(null, 9, new Thread());
<a name="238715"></a>		testFour(null, 9, new Thread());
<a name="238716"></a>		testFour(objects, 1, new StringBuffer());
<a name="238717"></a>		testFour(objects, 1, new Thread());
<a name="238718"></a>		testFour(objects, 9, new StringBuffer());
<a name="238719"></a>		testFour(objects, 9, new Thread());
<a name="238720"></a>		testFour(threads, 1, new StringBuffer());
<a name="238721"></a>		testFour(threads, 1, new Thread());
<a name="238722"></a>		testFour(threads, 9, new StringBuffer());
<a name="238723"></a>		testFour(threads, 9, new Thread());
<a name="238724"></a>	}
<br><a name="238725"></a>}
</pre><a name="238532"></a>
This program prints:
<p><pre><a name="238746"></a>
throw[throw]=throw =&gt; ArrayReferenceThrow
<a name="238747"></a>throw[throw]=Thread =&gt; ArrayReferenceThrow
<a name="238748"></a>throw[1]=throw =&gt; ArrayReferenceThrow
<a name="238749"></a>throw[1]=Thread =&gt; ArrayReferenceThrow
<br><a name="238751"></a>
null[throw]=throw =&gt; IndexThrow
<a name="238752"></a>null[throw]=StringBuffer =&gt; IndexThrow
<a name="238753"></a>null[1]=throw =&gt; RightHandSideThrow
<a name="238754"></a>null[1]=StringBuffer =&gt; NullPointerException
<br><a name="238756"></a>
null[throw]=throw =&gt; IndexThrow
<a name="238757"></a>null[throw]=StringBuffer =&gt; IndexThrow
<a name="238758"></a>null[1]=throw =&gt; RightHandSideThrow
<a name="238759"></a>null[1]=StringBuffer =&gt; NullPointerException
<br><a name="238761"></a>
null[throw]=throw =&gt; IndexThrow
<a name="238762"></a>null[throw]=Thread =&gt; IndexThrow
<a name="238763"></a>null[9]=throw =&gt; RightHandSideThrow
<a name="238764"></a>null[9]=Thread =&gt; NullPointerException
<br><a name="238766"></a>
null[throw]=throw =&gt; IndexThrow
<a name="238767"></a>null[throw]=Thread =&gt; IndexThrow
<a name="238768"></a>null[9]=throw =&gt; RightHandSideThrow
<a name="238769"></a>null[9]=Thread =&gt; NullPointerException
<br><a name="238771"></a>
Objects[throw]=throw =&gt; IndexThrow
<a name="238772"></a>Objects[throw]=StringBuffer =&gt; IndexThrow
<a name="238773"></a>Objects[1]=throw =&gt; RightHandSideThrow
<a name="238774"></a>Objects[1]=StringBuffer =&gt; Okay!
<br><a name="238776"></a>
Objects[throw]=throw =&gt; IndexThrow
<a name="238777"></a>Objects[throw]=Thread =&gt; IndexThrow
<a name="238778"></a>Objects[1]=throw =&gt; RightHandSideThrow
<a name="238779"></a>Objects[1]=Thread =&gt; Okay!
<br><a name="238781"></a>
Objects[throw]=throw =&gt; IndexThrow
<a name="238782"></a>Objects[throw]=StringBuffer =&gt; IndexThrow
<a name="238783"></a>Objects[9]=throw =&gt; RightHandSideThrow
<a name="238784"></a>Objects[9]=StringBuffer =&gt; IndexOutOfBoundsException
<br><a name="238786"></a>
Objects[throw]=throw =&gt; IndexThrow
<a name="238787"></a>Objects[throw]=Thread =&gt; IndexThrow
<a name="238788"></a>Objects[9]=throw =&gt; RightHandSideThrow
<a name="238789"></a>Objects[9]=Thread =&gt; IndexOutOfBoundsException
<br><a name="238791"></a>
Threads[throw]=throw =&gt; IndexThrow
<a name="238792"></a>Threads[throw]=StringBuffer =&gt; IndexThrow
<a name="238793"></a>Threads[1]=throw =&gt; RightHandSideThrow
<a name="238794"></a>Threads[1]=StringBuffer =&gt; ArrayStoreException
<br><a name="238796"></a>
Threads[throw]=throw =&gt; IndexThrow
<a name="238797"></a>Threads[throw]=Thread =&gt; IndexThrow
<a name="238798"></a>Threads[1]=throw =&gt; RightHandSideThrow
<a name="238799"></a>Threads[1]=Thread =&gt; Okay!
<br><a name="238801"></a>
Threads[throw]=throw =&gt; IndexThrow
<a name="238802"></a>Threads[throw]=StringBuffer =&gt; IndexThrow
<a name="238803"></a>Threads[9]=throw =&gt; RightHandSideThrow
<a name="238804"></a>Threads[9]=StringBuffer =&gt; IndexOutOfBoundsException
<br><a name="238806"></a>
Threads[throw]=throw =&gt; IndexThrow
<a name="238807"></a>Threads[throw]=Thread =&gt; IndexThrow
<a name="238808"></a>Threads[9]=throw =&gt; RightHandSideThrow
<a name="238809"></a>Threads[9]=Thread =&gt; IndexOutOfBoundsException
</pre><a name="238840"></a>
The most interesting case of the lot is the one thirteenth from the end:
<p><pre><a name="238843"></a>Threads[1]=StringBuffer =&gt; ArrayStoreException
</pre><a name="238841"></a>
which indicates that the attempt to store a reference to a <code>StringBuffer</code> into an 
array whose components are of type <code>Thread</code> throws an <code>ArrayStoreException</code>. 
The code is type-correct at compile time: the assignment has a left-hand side of 
type <code>Object[]</code> and a right-hand side of type <code>Object</code>. At run time, the first actual 
argument to method <code>testFour</code> is a reference to an instance of "array of <code>Thread</code>" 
and the third actual argument is a reference to an instance of class <code>StringBuffer</code>.
<p><a name="5304"></a>
<h3>15.25.2    Compound Assignment Operators</h3>
<a name="5305"></a>
All compound assignment operators require both operands to be of primitive type, 
except for <code>+=</code>, which allows the right-hand operand to be of any type if the left-
hand operand is of type <code>String</code>.
<p><a name="5306"></a>
A compound assignment expression of the form <i>E1</i> <i>op</i>= <i>E2</i> is equivalent to <i>E1</i> &#32;<code>=</code> &#32;<code>(</code><i>T</i><code>)((</code><i>E1</i><code>)</code> <i>op</i> <code>(</code><i>E2</i><code>))</code>, where <i>T</i> is the type of <i>E1</i>, except that <i>E1</i> is evaluated only once. Note that the implied cast to type <i>T</i> may be either an identity conversion <a href="5.doc.html#25209">(&#167;5.1.1)</a> or a narrowing primitive conversion <a href="5.doc.html#175672">(&#167;5.1.3)</a>. For example, the following code is correct:<p>
<pre><a name="236396"></a>
short x = 3;
<a name="236397"></a>x += 4.6;
</pre><a name="236398"></a>
and results in <code>x</code> having the value <code>7</code> because it is equivalent to:
<p><pre><a name="236400"></a>
short x = 3;
<a name="236401"></a>x = (short)(x + 4.6);
</pre><a name="238395"></a>
At run time, the expression is evaluated in one of two ways. If the left-hand operand expression is not an array access expression, then four steps are required:<p>
<ul><a name="238396"></a>
<li>First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
<a name="238397"></a>
<li>Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="238433"></a>
<li>Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see <a href="15.doc.html#5047">&#167;15.16.2</a>), then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="238398"></a>
<li>Otherwise, the result of the binary operation is converted to the type of the left-hand variable and the result of the conversion is stored into the variable.
</ul><a name="238402"></a>
If the left-hand operand expression is an array access expression <a href="15.doc.html#239587">(&#167;15.12)</a>, then 
many steps are required:
<p><ul><a name="238403"></a>
<li>First, the array reference subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index subexpression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
<a name="238404"></a>
<li>Otherwise, the index subexpression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
<a name="238449"></a>
<li>Otherwise, if the value of the array reference subexpression is <code>null</code>, then no assignment occurs and a <code>NullPointerException</code> &#32;is thrown.
<a name="238450"></a>
<li>Otherwise, the value of the array reference subexpression indeed refers to an array. If the value of the index subexpression is less than zero, or greater than &#32;or equal to the length of the array, then no assignment occurs and an <code>IndexOutOfBoundsException</code> &#32;is thrown.
<a name="238405"></a>
<li>Otherwise, the value of the index subexpression is used to select a component of the array referred to by the value of the array reference subexpression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs. (For a simple assignment operator, the evaluation of the right-hand operand occurs before the checks of the array reference subexpression and the index subexpression, but for a compound assignment operator, the evaluation of the right-hand operand occurs after these checks.)
<a name="238408"></a>
<li>Otherwise, consider the array component selected in the previous step, whose value was saved. This component is a variable; call its type <i>S</i><i></i>. Also, let <i>T</i> be the type of the left-hand operand of the assignment operator as determined at compile time.
<ul>
<a name="238409"></a>
<li>If <i>T</i> is a primitive type, then <i>S</i> is necessarily the same as <i>T</i>.
<ul>
<a name="238472"></a>
<li>The saved value of the array component and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly (the only possibility is an integer division by zero-see <a href="15.doc.html#5047">&#167;15.16.2</a>), then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="238476"></a>
<li>Otherwise, the result of the binary operation is converted to the type of the array component and the result of the conversion is stored into the array component.
</ul>
<a name="238410"></a>
<li>If <i>T</i> is a reference type, then it must be <code>String</code>. Because class <code>String</code> is a <code>final</code> class, <i>S</i> must also be <code>String</code>. Therefore the run-time check that is sometimes required for the simple assignment operator is never required for a compound assignment operator.
<ul>
<a name="238488"></a>
<li>The saved value of the array component and the value of the right-hand operand are used to perform the binary operation (string concatenation) indicated by the compound assignment operator (which is necessarily <code>+=</code>). If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
<a name="238492"></a>
<li>Otherwise, the <code>String</code> result of the binary operation is stored into the array component.
</ul>
</ul>
</ul><a name="238860"></a>
The rules for compound assignment to an array component are illustrated by the 
following example program:
<p><pre><br><a name="238863"></a>class ArrayReferenceThrow extends RuntimeException { }
<br><br><a name="238864"></a>class IndexThrow extends RuntimeException { }
<br><br><a name="238865"></a>class RightHandSideThrow extends RuntimeException { }
<br><a name="238867"></a>class IllustrateCompoundArrayAssignment {
<br><a name="238868"></a>	static String[] strings = { "Simon", "Garfunkel" };
<br><br><a name="238869"></a>	static double[] doubles = { Math.E, Math.PI };
<br></pre><pre><a name="238870"></a>
	static String[] stringsThrow() {
<a name="238983"></a>		throw new ArrayReferenceThrow();
<a name="238984"></a>	}
<br><a name="238871"></a>
	static double[] doublesThrow() {
<a name="238985"></a>		throw new ArrayReferenceThrow();
<a name="238986"></a>	}
<br><br><a name="238872"></a>	static int indexThrow() { throw new IndexThrow(); }
<br><a name="238873"></a>
	static String stringThrow() {
<a name="238987"></a>		throw new RightHandSideThrow();
<a name="238988"></a>	}
<br><a name="238874"></a>
	static double doubleThrow() {
<a name="238989"></a>		throw new RightHandSideThrow();
<a name="238990"></a>	}
<br><a name="238875"></a>
	static String name(Object q) {
<a name="238876"></a>		String sq = q.getClass().getName();
<a name="238877"></a>		int k = sq.lastIndexOf('.');
<a name="238878"></a>		return (k &lt; 0) ? sq : sq.substring(k+1);
<a name="238879"></a>	}
<br><a name="238880"></a>
	static void testEight(String[] x, double[] z, int j) {
<a name="238881"></a>		String sx = (x == null) ? "null" : "Strings";
<a name="238882"></a>		String sz = (z == null) ? "null" : "doubles";
<a name="238883"></a>		System.out.println();
<a name="238884"></a>		try {
<a name="238885"></a>			System.out.print(sx + "[throw]+=throw =&gt; ");
<a name="238886"></a>			x[indexThrow()] += stringThrow();
<a name="238887"></a>			System.out.println("Okay!");
<a name="238888"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238889"></a>		try {
<a name="238890"></a>			System.out.print(sz + "[throw]+=throw =&gt; ");
<a name="238891"></a>			z[indexThrow()] += doubleThrow();
<a name="238892"></a>			System.out.println("Okay!");
<a name="238893"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238894"></a>
		try {
<a name="238895"></a>			System.out.print(sx + "[throw]+=\"heh\" =&gt; ");
<a name="238896"></a>			x[indexThrow()] += "heh";
<a name="238897"></a>			System.out.println("Okay!");
<a name="238898"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238899"></a>		try {
<a name="238900"></a>			System.out.print(sz + "[throw]+=12345 =&gt; ");
<a name="238901"></a>			z[indexThrow()] += 12345;
<a name="238902"></a>			System.out.println("Okay!");
<a name="238903"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238904"></a>		try {
<a name="238905"></a>			System.out.print(sx + "[" + j + "]+=throw =&gt; ");
<a name="238906"></a>			x[j] += stringThrow();
<a name="238907"></a>			System.out.println("Okay!");
<a name="238908"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238909"></a>		try {
<a name="238910"></a>			System.out.print(sz + "[" + j + "]+=throw =&gt; ");
<a name="238911"></a>			z[j] += doubleThrow();
<a name="238912"></a>			System.out.println("Okay!");
<a name="238913"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238914"></a>		try {
<a name="238915"></a>			System.out.print(sx + "[" + j + "]+=\"heh\" =&gt; ");
<a name="238916"></a>			x[j] += "heh";
<a name="238917"></a>			System.out.println("Okay!");
<a name="238918"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238919"></a>		try {
<a name="238920"></a>			System.out.print(sz + "[" + j + "]+=12345 =&gt; ");
<a name="238921"></a>			z[j] += 12345;
<a name="238922"></a>			System.out.println("Okay!");
<a name="238923"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238924"></a>	}
<br><a name="238925"></a>
	public static void main(String[] args) {
<a name="238926"></a>		try {
<a name="238927"></a>			System.out.print("throw[throw]+=throw =&gt; ");
<a name="238928"></a>			stringsThrow()[indexThrow()] += stringThrow();
<a name="238929"></a>			System.out.println("Okay!");
<a name="238930"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238931"></a>		try {
<a name="238932"></a>			System.out.print("throw[throw]+=throw =&gt; ");
<a name="238933"></a>			doublesThrow()[indexThrow()] += doubleThrow();
<a name="238934"></a>			System.out.println("Okay!");
<a name="238935"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238936"></a>		try {
<a name="238937"></a>			System.out.print("throw[throw]+=\"heh\" =&gt; ");
<a name="238938"></a>			stringsThrow()[indexThrow()] += "heh";
<a name="238939"></a>			System.out.println("Okay!");
<a name="238940"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238941"></a>
		try {
<a name="238942"></a>			System.out.print("throw[throw]+=12345 =&gt; ");
<a name="238943"></a>			doublesThrow()[indexThrow()] += 12345;
<a name="238944"></a>			System.out.println("Okay!");
<a name="238945"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238946"></a>		try {
<a name="238947"></a>			System.out.print("throw[1]+=throw =&gt; ");
<a name="238948"></a>			stringsThrow()[1] += stringThrow();
<a name="238949"></a>			System.out.println("Okay!");
<a name="238950"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238951"></a>		try {
<a name="238952"></a>			System.out.print("throw[1]+=throw =&gt; ");
<a name="238953"></a>			doublesThrow()[1] += doubleThrow();
<a name="238954"></a>			System.out.println("Okay!");
<a name="238955"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238956"></a>		try {
<a name="238957"></a>			System.out.print("throw[1]+=\"heh\" =&gt; ");
<a name="238958"></a>			stringsThrow()[1] += "heh";
<a name="238959"></a>			System.out.println("Okay!");
<a name="238960"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238961"></a>		try {
<a name="238962"></a>			System.out.print("throw[1]+=12345 =&gt; ");
<a name="238963"></a>			doublesThrow()[1] += 12345;
<a name="238964"></a>			System.out.println("Okay!");
<a name="238965"></a>		} catch (Throwable e) { System.out.println(name(e)); }
<a name="238966"></a>
		testEight(null, null, 1);
<a name="238967"></a>		testEight(null, null, 9);
<a name="238968"></a>		testEight(strings, doubles, 1);
<a name="238969"></a>		testEight(strings, doubles, 9);
<a name="238970"></a>	}
<br><a name="238971"></a>}
</pre><a name="238992"></a>
This program prints:
<p><pre><a name="238994"></a>
throw[throw]+=throw =&gt; ArrayReferenceThrow
<a name="238995"></a>throw[throw]+=throw =&gt; ArrayReferenceThrow
<a name="238996"></a>throw[throw]+="heh" =&gt; ArrayReferenceThrow
<a name="238997"></a>throw[throw]+=12345 =&gt; ArrayReferenceThrow
<a name="238998"></a>throw[1]+=throw =&gt; ArrayReferenceThrow
<a name="238999"></a>throw[1]+=throw =&gt; ArrayReferenceThrow
<a name="239000"></a>throw[1]+="heh" =&gt; ArrayReferenceThrow
<a name="239001"></a>throw[1]+=12345 =&gt; ArrayReferenceThrow
<br><a name="239003"></a>
null[throw]+=throw =&gt; IndexThrow
<a name="239004"></a>null[throw]+=throw =&gt; IndexThrow
<a name="239005"></a>null[throw]+="heh" =&gt; IndexThrow
<a name="239006"></a>null[throw]+=12345 =&gt; IndexThrow
<a name="239007"></a>null[1]+=throw =&gt; NullPointerException
<a name="239008"></a>null[1]+=throw =&gt; NullPointerException
<a name="239009"></a>null[1]+="heh" =&gt; NullPointerException
<a name="239010"></a>null[1]+=12345 =&gt; NullPointerException
<br><a name="239012"></a>
null[throw]+=throw =&gt; IndexThrow
<a name="239013"></a>null[throw]+=throw =&gt; IndexThrow
<a name="239014"></a>null[throw]+="heh" =&gt; IndexThrow
<a name="239015"></a>null[throw]+=12345 =&gt; IndexThrow
<a name="239016"></a>null[9]+=throw =&gt; NullPointerException
<a name="239017"></a>null[9]+=throw =&gt; NullPointerException
<a name="239018"></a>null[9]+="heh" =&gt; NullPointerException
<a name="239019"></a>null[9]+=12345 =&gt; NullPointerException
<br><a name="239021"></a>
Strings[throw]+=throw =&gt; IndexThrow
<a name="239022"></a>doubles[throw]+=throw =&gt; IndexThrow
<a name="239023"></a>Strings[throw]+="heh" =&gt; IndexThrow
<a name="239024"></a>doubles[throw]+=12345 =&gt; IndexThrow
<a name="239025"></a>Strings[1]+=throw =&gt; RightHandSideThrow
<a name="239026"></a>doubles[1]+=throw =&gt; RightHandSideThrow
<a name="239027"></a>Strings[1]+="heh" =&gt; Okay!
<a name="239028"></a>doubles[1]+=12345 =&gt; Okay!
<br><a name="239030"></a>
Strings[throw]+=throw =&gt; IndexThrow
<a name="239031"></a>doubles[throw]+=throw =&gt; IndexThrow
<a name="239032"></a>Strings[throw]+="heh" =&gt; IndexThrow
<a name="239033"></a>doubles[throw]+=12345 =&gt; IndexThrow
<a name="239034"></a>Strings[9]+=throw =&gt; IndexOutOfBoundsException
<a name="239035"></a>doubles[9]+=throw =&gt; IndexOutOfBoundsException
<a name="239036"></a>Strings[9]+="heh" =&gt; IndexOutOfBoundsException
<a name="239037"></a>doubles[9]+=12345 =&gt; IndexOutOfBoundsException
</pre><a name="239051"></a>
The most interesting cases of the lot are tenth and eleventh from the end:
<p><pre><a name="239058"></a>
Strings[1]+=throw =&gt; RightHandSideThrow
<a name="239059"></a>doubles[1]+=throw =&gt; RightHandSideThrow
</pre><a name="238861"></a>
They are the cases where a right-hand side that throws an exception actually gets 
to throw the exception; moreover, they are the only such cases in the lot. This 
demonstrates that the evaluation of the right-hand operand indeed occurs after the 
checks for a null array reference value and an out-of-bounds index value.
<p><a name="240007"></a>
The following program illustrates the fact that the value of the left-hand side of a compound assignment is saved before the right-hand side is evaluated:<p>
<pre><a name="240010"></a>
class Test {
<a name="240011"></a>	public static void main(String[] args) {
<a name="240012"></a>		int k = 1;
<a name="240013"></a>		int[] a = { 1 };
<a name="240032"></a>		k += (k = 4) * (k + 2);
<a name="240016"></a>		a[0] += (a[0] = 4) * (a[0] + 2);
<a name="240041"></a>		System.out.println("k==" + k + " and a[0]==" + a[0]);
<a name="240017"></a>	}
<a name="240018"></a>}
</pre><a name="240021"></a>
This program prints:
<p><pre><a name="240024"></a>k==25 and a[0]==25
</pre><a name="240027"></a>
The value <code>1</code> of <code>k</code> is saved by the compound assignment operator <code>+=</code> before its 
right-hand operand <code>(k</code> <code>=</code> <code>4)</code> <code>*</code> <code>(k</code> <code>+</code> <code>2)</code> is evaluated. Evaluation of this right-hand 
operand then assigns <code>4</code> to <code>k</code>, calculates the value <code>6</code> for <code>k</code> <code>+</code> <code>2</code>, and then multiplies 
<code>4</code> &#32;by &#32;<code>6</code> to get <code>24</code>. This is added to the saved value <code>1</code> to get <code>25</code>, which is then stored 
into <code>k</code> by the <code>+=</code> operator. An identical analysis applies to the case that uses <code>a[0]</code>. 
In short, the statements
<p><pre><a name="240068"></a>
k += (k = 4) * (k + 2);
<a name="240069"></a>a[0] += (a[0] = 4) * (a[0] + 2);
</pre><a name="240066"></a>
behave in exactly the same manner as the statements:
<p><pre><a name="240072"></a>
k = k + (k = 4) * (k + 2);
<a name="240073"></a>a[0] = a[0] + (a[0] = 4) * (a[0] + 2);
</pre><a name="5308"></a>
<h2>15.26    Expression</h2>
<a name="5309"></a>
An <i>Expression</i> is any assignment expression:
<p><ul><pre>
<i>Expression:<br>
</i>	<i>AssignmentExpression
</i></pre></ul><a name="5311"></a>
Unlike C and C++, the Java language has no comma operator.
<p><a name="5313"></a>
<h2>15.27    Constant Expression</h2>
<ul><pre>
<i>ConstantExpression:<br>
</i>	<i>Expression
</i></pre></ul><a name="5314"></a>
A compile-time <i>constant expression</i> is an expression denoting a value of primitive type or a <code>String</code> that is composed using only the following:<p>
<ul><a name="236320"></a>
<li>Literals of primitive type and literals of type <code>String</code>
<a name="236323"></a>
<li>Casts to primitive types and casts to type <code>String</code>
<a name="236324"></a>
<li>The unary operators <code>+</code>, <code>-</code>, <code>~</code>, and <code>! </code>(but not <code>++</code> or <code>--</code>)
<a name="239222"></a>
<li>The multiplicative operators <code>*</code>, <code>/</code>, and <code>%</code>
<a name="239261"></a>
<li>The additive operators <code>+</code> and <code>-</code>
<a name="239263"></a>
<li>The shift operators <code>&lt;&lt;</code>, <code>&gt;&gt;</code>, and <code>&gt;&gt;&gt;</code>
<a name="239226"></a>
<li>The relational operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;= </code>(but not <code>instanceof</code>)
<a name="239228"></a>
<li>The equality operators <code>==</code> and <code>!=</code>
<a name="239255"></a>
<li>The bitwise and logical operators <code>&amp;</code>, <code>^</code>, and <code>|</code>
<a name="239257"></a>
<li>The conditional-and operator <code>&amp;&amp;</code> and the conditional-or operator <code>||</code>
<a name="236327"></a>
<li>The ternary conditional operator <code>?</code>&#32;<code>:</code>
<a name="8720"></a>
<li>Simple names that refer to <code>final</code> variables whose initializers are constant expressions
<a name="239286"></a>
<li>Qualified names of the form <i>TypeName</i> <code>.</code> <i>Identifier</i> that refer to <code>final</code> variables whose initializers are constant expressions
</ul><a name="5315"></a>
Compile-time constant expressions are used in <code>case</code> labels in <code>switch</code> statements 
<a href="14.doc.html#35518">(&#167;14.9)</a> and have a special significance for assignment conversion <a href="5.doc.html#170768">(&#167;5.2)</a>.
<p><a name="236407"></a>
Examples of constant expressions:<p>
<pre><a name="236408"></a>true
<a name="236411"></a>(short)(1*2*3*4*5*6)
<a name="236409"></a>Integer.MAX_VALUE / 2
<a name="239216"></a>2.0 * Math.PI
<a name="236410"></a>"The integer " + Long.MAX_VALUE + " is mighty big."
</pre>

<hr>
<!-- This inserts footnotes-->
<table border="0" width="100%">
<tr>
<td><a href="index.html">Contents</a> | <a href="14.doc.html">Prev</a> | <a href="16.doc.html">Next</a> | <a href="j.index.doc1.html">Index</a></td>
<td align=right><i>Java Language Specification</i><br>
<font size="-1">First Edition</font></td></tr></table>
<p>
<font size=-1>Java Language Specification (HTML generated by Suzette Pelouch on April 03, 1998)<br>
<i><a href="jcopyright.doc.html">Copyright &#169 1996 Sun Microsystems, Inc.</a>
All rights reserved</i>
<br>
Please send any comments or corrections via our <a href="http://developers.sun.com/contact/feedback.jsp?&category=doc&mailsubject=Java%20Language%20Specification%20Feedback">feedback form</a>
</font>
<script language="JavaScript" src="/js/omi/jsc/s_code_remote.js"></script></body></html>